Java project: crm customer relationship management system (java+SpringBoot+ECharts+Freemarker+Layui+maven+mysql)

Get the source code: Download it from "Resources" on the homepage of the blog!

CRM Smart Office

Project Introduction

This application is a customer relationship management system, mainly including five modules, namely marketing management, customer management, service management, statistical reports and system management, providing simple data management and analysis for customer relationship management

In terms of technology selection, the project is a single application of `SpringBoot`. The project uses the `SpringBoot2` framework for rapid development, the data access layer uses the `Mybatis` framework, the page rendering engine uses `Freemarker`, and the page style uses `Layui`. Logback uses `logback`, statistical report part uses `ECharts`, and the database uses Mysql 8.0;
 

Installation tutorial

1. Create a database named `crm` in mysql (mysql8 by default), and execute the `crm.sql` script in the root directory of the source code to generate database tables and data
2. Import the project source code into idea and specify the jdk version of the project For jdk8 or above, and mark it as a maven project, download the required dependencies
3. Modify the database configuration in `application.yml` (mainly database name and database password)
4. Modify logback.xml, line 4, log The storage address of the file is changed to its own path;

5. Check whether the startup project is normal. The default startup address home page is `http://localhost:1212/crm`, the default database administrator is `admin`, and the password is `123456`. You can modify the user after logging in to the system. password

 

 

 

 

 

 

User management control layer:

/**
 * @author yy
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    IUserService userService;
    
    @Autowired
    IRoleService roleService;
    
    @Autowired
    RedisUtil redisUtil;
    
    @Autowired
    MailUtil mailUtil;
    
    Logger logger = LoggerFactory.getLogger(UserController.class);
    
    /**
     * 描述:查找用户
     * @param page
     * @param limit
     * @param user
     * @return
     */
    @Operation(name="查找用户")
    @RequiresPermissions("1001")
    @RequestMapping("/findUser")
    @ResponseBody
    public Map<String, Object> findUser(Integer page,Integer limit, User user){
        
        Map<String, Object> map = new HashMap<String,Object>(16);
        
        //创建用户模板类
        UserExample userExample = new UserExample();
        //创建查询准则
        Criteria criteria = userExample.createCriteria();
        if(page == null || page <= 0) {
            page = 1;
        }
        if(limit == null || limit <= 0) {
            limit = 10;
        }
        
        //判断user类的条件是否为空
        if(user.getRealName() != null) {
             criteria.andRealNameLike("%"+user.getRealName()+"%");
        }
        
        if(user.getRoleId() != null) {
            logger.info("获得到的角色编号为:" + user.getRoleId());
            criteria.andRoleIdEqualTo(user.getRoleId());
        }
        
        if(user.getAccount() != null) {
            criteria.andAccountLike("%"+user.getAccount()+"%");
        }
        
        Long offset = new Long((page - 1) * limit);
        
        Long count = userService.countByExample(userExample);
        
        userExample.setLimit(limit);
        userExample.setOffset(offset);
        
        List<User> list = userService.findByExample(userExample);
        
        logger.info(list.toString());
        
        map.put("data", list);
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", count);
        return map;
    }
    
    /**
     * 
     * 描述:根据编号查找用户
     * @author wanghaoyu
     * @version 1.0
     * @param id
     * @return 
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="根据编号查找用户")
    @RequiresAuthentication
    @RequestMapping("/findUserById")
    @ResponseBody
    public Map<String, Object> findUserById(Integer id){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        String msg = "";
        User user = userService.findById(id);
        if(user != null){
             user.setPassword(null);
             user.setSalt(null);
            success = true;
        }else{
            msg = "读取用户数据出错,请稍后再试!";
        }
        map.put("success", success);
        map.put("user", user);
        map.put("msg",msg);
        map.put("code", 0);
        return map;
    }
    
    /**
     * 
     * 描述:根据用户ID删除用户
     * @author wanghaoyu
     * @version 1.0
     * @param id 用户编号
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="删除用户")
    @RequiresPermissions("1004")
    @RequestMapping("/deleteUser")
    @ResponseBody
    public Map<String, Object> deleteUser(Integer id){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        //删除成功
        if(userService.deleteById(id) == true) {
            success = true;
        }
        map.put("success", success);
        map.put("code", 0);
        return map;
    }
    
    /**
     * 
     * 描述:编辑用户
     * @author wanghaoyu
     * @version 1.0
     * @param user 要编辑的用户信息
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="修改用户")
    @RequiresPermissions(value={"1002","13002"}, logical=Logical.OR)
    @RequestMapping("/editUser")
    @ResponseBody
    public Map<String, Object> editUser(User user){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        String msg = "";
        //修改成功
        if(userService.edit(user) == true) {
            success = true;
            msg = "修改成功!";
        }else {
            msg = "修改失败!";
        }
        map.put("success", success);
        map.put("msg", msg);
        map.put("code", 0);
        return map;
    }
    
    /**
     * 
     * 描述:添加用户
     * @author wanghaoyu
     * @version 1.0
     * @param user 要添加的用户信息
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="添加用户")
    @RequiresPermissions("1003")
    @RequestMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(User user){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        
        //设置user的初始密码为123456
        user.setPassword("123456");
        
        //添加
        if(userService.save(user) == true) {
            success = true;
        }
        map.put("success", success);
        map.put("code", 0);
        return map;
    }
    
    /**
     * 
     * 描述:查找所有的角色
     * @author wanghaoyu
     * @version 1.0
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="后台查找角色列表")
    @RequiresAuthentication
    @RequestMapping("/findRoles")
    @ResponseBody
    public Map<String, Object> findRoles(){
        Map<String, Object> map = new HashMap<String, Object>(16);
        List<Role> roles = roleService.selectByRoleExample(new RoleExample());
        map.put("success", true);
        map.put("list", roles);
        logger.info(roles.toString());
        return map;
    }
    
    /**
     * 
     * 描述:查找除当前登录的客户经理外的所有的客户经理
     * @author wanghaoyu
     * @version 1.0
     * @param request
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="后台查找其他客户经理角色")
    @RequiresAuthentication
    @RequestMapping("/findOthersManager")
    @ResponseBody
    public Map<String, Object> findOthersManager(HttpServletRequest request){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        //获取当前登录用户
        User user = (User)request.getSession().getAttribute("user");
        //创建用户模块
        UserExample userExample = new UserExample();
        //创建查询准则
        Criteria criteria =  userExample.createCriteria();
        //如果当前用户为客户经理
        if(user.getRoleId() == 1) {
            criteria.andIdNotEqualTo(user.getId());
        }
        criteria.andRoleIdEqualTo(1);
        List<User> users = userService.findByExample(userExample);
        success = true; 
        
        map.put("success", success);
        map.put("list", users);
        map.put("code", 0);
        return map;
    }
    
    /**
     * 
     * 描述:检查用户账号是否可用
     * @author wanghaoyu
     * @version 1.0
     * @param account
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="检查用户账号")
    @RequestMapping("/checkUserAccount")
    @ResponseBody
    public Map<String, Object> checkUserAccount(String account){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        //没有找到该账号名,说明账号可用
        if(userService.findByAccount(account) == null) {
            success = true;
        }
        map.put("success", success);
        map.put("code", 0);
        return map;
    }
    
    /**
     * 
     * 描述:检查用户邮箱是否可用
     * @author wanghaoyu
     * @version 1.0
     * @param email
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="检查用户邮箱")
    @RequestMapping("/checkUserEmail")
    @ResponseBody
    public Map<String, Object> checkUserEmail(String email){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        //没有找到该账号名,说明邮箱可用
        if(userService.findByEmail(email) == null) {
            success = true;
        }
        map.put("success", success);
        map.put("code", 0);
        return map;
    }
    
    /**
     * 
     * 描述:根据session域里面的用户编号查找当前登录的用户
     * @author wanghaoyu
     * @version 1.0
     * @param id
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="查找当前登录的用户")
    @RequiresPermissions("13001")
    @RequestMapping("/findCurrentUser")
    @ResponseBody
    public Map<String, Object> findCurrentUser(Integer id){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        String msg = "";
        //根据ID查找用户
        User user = userService.findById(id);
        if(user != null){
            user.setPassword(null);
            user.setSalt(null);
            success = true;
            msg = "查找成功!";
        }else{
            success = false;
            msg = "查找失败!";
        }
        map.put("success", success);
        map.put("code",0);
        map.put("data", user);
        map.put("msg", msg);
        return map;
    }
    
    
    /**
     * 
     * 描述:用户修改密码
     * @author wanghaoyu
     * @version 1.0
     * @param user
     * @return Map<String,Object>
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="修改用户密码")
    @RequiresPermissions("14001")
    @RequestMapping("/editUserPasswd")
    @ResponseBody
    public Map<String, Object> editUserPasswd(User user,String oldPassword){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        String msg = "";
        if(userService.editPasswd(user,oldPassword)) {
            success = true;
            msg = "修改成功!";
        }else {
            success = false;
            msg = "修改失败!";
        }
        map.put("success", success);
        map.put("msg", msg);
        map.put("code", 0);
        return map;
    }
    
    /**
     * 
     * 描述:获取忘记密码时的验证码
     * @author wanghaoyu
     * @version 1.0
     * @param email
     * @return 
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="获取找回密码所需的验证码")
    @RequestMapping("/getForgotPasswdCode")
    @ResponseBody
    public Map<String, Object> getForgotPasswdCode(String email){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        String msg = "";
        if(userService.findByEmail(email) == null){
            //找不到该邮箱的账号
            msg = "不存在的账号!";
        }else{
            try {
                //生成长度为4的随机数字
                String code = RandomStringUtil.getRandomCode(4, 0);
                //存到redis缓存中,有效时间为5分钟
                //先删除原来已存在的验证码
                redisUtil.remove(email);
                redisUtil.set(email, code, 300L);
                //发送邮件
                mailUtil.send(email, "找回密码", "验证码:" + code + "(验证码有效期为5分钟)");
                success = true;
                msg = "发送验证码成功!";
            } catch (Exception e) {
                e.printStackTrace();
                msg = "获取验证码失败!";
            }
        }
        map.put("success", success);
        map.put("code", 0);
        map.put("msg", msg);
        return map;
    }
    
    /**
     * 
     * 描述: 重设密码
     * @author wanghaoyu
     * @version 1.0
     * @param email
     * @return 
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="重设密码")
    @RequestMapping("/resetPasswd")
    @ResponseBody
    public Map<String, Object> resetPasswd(String email, String code, String password){
        Map<String, Object> map = new HashMap<String, Object>(16);
        boolean success = false;
        String msg = "";
        try {
            //先根据邮箱获取相应用户的信息
            User user = userService.findByEmail(email);
            if(user == null){
                msg = "不存在的账号!";
            }else{
                //从redis缓存中获取验证码
                if(redisUtil.exists(email)){
                    String redisCode = (String) redisUtil.get(email);
                    if(redisCode.equals(code)){
                        //验证码正确,修改密码
                        User editUser = new User();
                        editUser.setId(user.getId());
                        editUser.setPassword(password);
                        if(userService.edit(editUser)){
                            msg = "修改成功!";
                            success = true;
                        }else{
                            msg = "修改失败!";
                        }
                    }else{
                        msg = "验证码错误!";
                    }
                }else{
                    msg = "验证码已过期,请重新获取!";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = "服务器出了小差,请稍等...";
        }
        map.put("success", success);
        map.put("code", 0);
        map.put("msg", msg);
        return map;
    }
    
    
}

Customer management control layer:

/**
 * 
 * @author yy
 */
@Controller
@RequestMapping("customer")
public class CustomerController {
    @Autowired
    private ICustomerService customerService;
    
    private User user = null;

    /**
     * @author huangwanzong
     * @date 2018年7月6日
     */
    private User getUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        user = (User)session.getAttribute("user");
        return user;
    }
    

    /**
     * 
     * 描述:分页查询客户
     * @author huangwanzong
     * @date 2018/07/06
     * @version 1.0
     * @param page 可选参数,查询的页数,默认值 1
     * @param limit 可选参数,分页的大小,默认值 10
     * @param customer 可选参数,查询的条件
     * @param findtype 可选参数,该参数值为 all 时不执行分页查询,返回全部符合条件的客户
     * @param request
     * @return Map<String,Object>
     * @since 1.8
     *
     */
    
    @RequiresPermissions("5001")
    @Operation(name="分页查询客户")
    @RequestMapping("list")
    @ResponseBody
    public Map<String, Object> listCustomer(Integer page,Integer limit,Customer customer,String findtype,HttpServletRequest request){
        Map<String, Object> map = new HashMap<String,Object>(16);
        
        //获取用户
        user = this.getUser(request);
        //检验用户正确性
        if(user == null || user.getId() == null) {
            map.put("code", -1);
            map.put("msg", "用户不存在,无法执行操作.");
            return map;
        }
        
        CustomerExample example = new CustomerExample();
        Criteria criteria = example.createCriteria();
        
        //设置分页参数
        if(page == null || page <= 0) {
            page = 1;
        }
        if(limit == null || limit <= 0) {
            limit = 10;
        }
        String all = "all";
        if(!all.equals(findtype)) {
            example.setLimit(limit);
            Long offset = new Long((page-1)*limit);
            example.setOffset(offset);
        }

        //设置管理者ID
        criteria.andManagerIdEqualTo(user.getId());
        //只查询未删除的客户
        criteria.andDeleteStatusEqualTo(0);
        System.out.println(customer);
        //检测属性是否存在,存在则进行条件查询
        if(customer != null) {
            if(customer.getName() != null) {
                criteria.andNameLike("%" + customer.getName() + "%");
            }
            
            if(customer.getType() != null && !"".equals(customer.getType())) {
                criteria.andTypeEqualTo(customer.getType()); 
            }
            if(customer.getStatus() != null && !"".equals(customer.getStatus())) {
                criteria.andStatusEqualTo(customer.getStatus());
            }
            if(customer.getSource() != null && !"".equals(customer.getSource())) {
                criteria.andSourceEqualTo(customer.getSource());
            }
            if(customer.getLevel() != null && !"".equals(customer.getLevel())) {
                criteria.andLevelEqualTo(customer.getLevel());
            }
            if(customer.getCredit() != null && !"".equals(customer.getCredit())) {
                criteria.andCreditEqualTo(customer.getCredit());
            }
            if(customer.getMaturity() != null && !"".equals(customer.getMaturity())) {
                criteria.andMaturityEqualTo(customer.getMaturity());
            }
        }
        
        Long count = customerService.countByCustomerExample(example);
        List<Customer> customers = customerService.selectByCustomerExample(example);
        
        map.put("data", customers);
        map.put("count", count);
        map.put("code", 0);
        
        return map;
    }
    
    
    /**
     * 
     * 描述:添加一个客户
     * @author huangwanzong
     * @date 2018/07/17
     * @version 1.0
     * @param customer 客户信息
     * @param linkman 联系人信息
     * @param customerName 客户名称
     * @param linkmanName 联系人名称
     * @param customerLevel 客户等级
     * @param request
     * @return Map<String,Object>
     * @since 1.8
     *
     */
    @RequiresPermissions("5002")
    @Operation(name="添加客户")
    @RequestMapping("add")
    @ResponseBody
    public Map<String, Object> addCustomer(Customer customer,Linkman linkman,String customerName,String linkmanName,String customerLevel,HttpServletRequest request){
        Map<String, Object> map = new HashMap<String,Object>(16);
        
        this.getUser(request);
        
        //检测是否存在customer对象
        if(customer == null || linkman == null) {
            map.put("msg", "参数为空");
            map.put("success", false);
            return map;
        }
        
        //检测客户名是否存在
        if(customerName == null || "".equals(customerName)) {
            map.put("msg", "用户名称参数不能为空");
            map.put("success", false);
            return map;
        }
        
        //检测联系人姓名是否存在
        if(linkmanName == null || "".equals(linkmanName)) {
            map.put("msg", "联系人名称参数不能为空");
            map.put("success", false);
            return map;
        }
        
        //客户所属者默认为创建者
        customer.setManagerId(user.getId());
        //设置创建者id
        customer.setCreater(user.getId());
        //设置创建时间
        customer.setCreateTime(LocalDateTime.now());
        //设置客户名称
        customer.setName(customerName);
        //设置客户等级
        customer.setLevel(customerLevel);
        //设置未删除
        customer.setDeleteStatus(0);
        
        //设置联系人名称
        linkman.setName(linkmanName);
     
        
        //进行数据插入
        if(customerService.insertSelective(customer,linkman)) {
            map.put("msg", "添加成功");
            map.put("success", true);
        }else {
            map.put("msg", "添加失败");
            map.put("success", false);
        }
        
        return map;
    }
    
    @RequiresPermissions("7009")
    @Operation(name="检测客户名称是否存在")
    @RequestMapping("checkname")
    @ResponseBody
    public boolean checkCustomerName(String name){
        
        CustomerExample example = new CustomerExample();
        example.createCriteria().andNameEqualTo(name);
        
        List<Customer> list = customerService.selectByCustomerExample(example);
        if(list.size()>0) {
            return true;
        }
        return false;
    }
    
    @RequiresPermissions("5003")
    @Operation(name="更新客户信息")
    @RequestMapping("update")
    @ResponseBody
    public Map<String, Object> updateCustomer(Customer customer){
        Map<String, Object> map = new HashMap<String,Object>(16);
 
        if(customerService.updateCustomerByPrimaryKeySelective(customer)) {
            map.put("msg", "更新成功");
            map.put("success", true);
        }else {
            map.put("msg", "更新失败");
            map.put("success", false); 
        }
        return map;
    }
    
    @RequiresPermissions("5004")
    @Operation(name="删除客户")
    @RequestMapping("delete")
    @ResponseBody
    public Map<String, Object> deleteCustomer(int[] ids){
        Map<String, Object> map = new HashMap<String,Object>(16);
        List<Integer> success = new ArrayList<Integer>();
        List<Integer> fail = new ArrayList<Integer>();
        for(int id : ids) {
            if(customerService.deleteByPrimaryKey(id)) {
                success.add(id);
            }else {
                fail.add(id);
            }
        }
        
        map.put("msg", "删除完成");
        map.put("status", true);
        map.put("success", success);
        map.put("fail", fail);
        
        return map;
    }
    
    @RequiresPermissions("7010")
    @Operation(name="id查找客户")
    @RequestMapping("find")
    @ResponseBody
    public Map<String, Object> findCustomer(Integer id){
        Map<String, Object> map = new HashMap<String,Object>(16);
        Customer customer = null;
        
        if(id == null) {
            map.put("msg", "非法操作");
            map.put("success", false); 
            return map;
        }
        
        customer = customerService.selectCustomerByPrimaryKey(id);
        
        if(customer != null) {
            map.put("msg", "查找成功");
            map.put("success", true);
            map.put("data", customer);
        }else {
            map.put("msg", "查找失败");
            map.put("success", false); 
        }
        return map;
    }
    
    
}

Log in to the management control layer: 

/**
 * 
 * @author yy
 * 
 */
@Controller
@RequestMapping("/user")
public class LoginController {
    
    @Autowired
    private IUserService userService;
    
    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    
    /**
     * 
     * 描述:登陆
     * @author wanghaoyu
     * @version 1.0
     * @param user 用户
     * @param verifyCode 验证码
     * @param request 请求
     * @return Map<String,Object> map封装要返回到前端的信息
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="登陆")
    @RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(User user, String verifyCode, 
            HttpServletRequest request){

    	Map<String, Object> maps = new HashMap<String, Object>(16);
    	
    	//1. 验证验证码
    	if(verifyCode == null || "".equals(verifyCode) ) {
    		maps.put("code", 200);
    		maps.put("msg", "请输入验证码");
    		return maps;
    	}
    	verifyCode = verifyCode.toLowerCase();
    	String sessionCode = (String) request.getSession().getAttribute("verifyCode");
    	if( sessionCode == null || "".equals(sessionCode)){
    		maps.put("code", 200);
    		maps.put("msg", "验证码获取失败! 请刷新页面!");
    		return maps;
    	}
    	sessionCode = sessionCode.toLowerCase();
    	
    	if(!sessionCode.equals(verifyCode)) {
    		maps.put("code", 200);
    		maps.put("msg", "验证码不正确!");
    		return maps;
    	}
    	
    	//2.判断用户账号密码
        Subject subject = SecurityUtils.getSubject();
        
        System.err.println("==============================" +subject.isAuthenticated());
        
        //判断用户是否已经登陆
        if(!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(),user.getPassword());
            try {
                subject.login(token);
                //验证成功
                //登陆成功后的用户账号信息
                String account =  (String)subject.getPrincipal();
                
                //根据用户账号,查询用户,并保存到session域中
                User loginUser = userService.findByAccount(account);
  
                LocalDateTime now = LocalDateTime.now();
                
                //如果上次登陆的时间为空,则说明这次是首次登陆,前台应该跳转到修改密码界面
                if(loginUser.getLastLoginTime() == null) {
                    maps.put("firstLogin", true);
                }
                //修改最后一次登录的时间,并保存到数据库
                loginUser.setLastLoginTime(now);
                loginUser.setPassword(null);
                
                //新创建对象用来更新user的最后一次登录时间
                User updateUser = new User();
                updateUser.setId(loginUser.getId());
                updateUser.setLastLoginTime(now);
                userService.edit(updateUser);
                
                request.getSession().setAttribute("user", loginUser);
                logger.info("登陆的用户信息:" + loginUser.toString());

                request.getSession().setAttribute("user", loginUser);
                maps.put("code", 0); 
              //账号被锁定
            } catch(LockedAccountException e){
                maps.put("code",200);
                maps.put("msg","账号已被锁定,请联系管理员进行处理!");
              //不存在的账号
            } catch(UnknownAccountException e) {
                maps.put("code",200);
                maps.put("msg","账号或密码错误!");
              //密码错误
            } catch(IncorrectCredentialsException e) {
                maps.put("code",200);
                maps.put("msg","账号或密码错误!");
            }catch (Exception e) {
                e.printStackTrace();
                maps.put("code", 200);
                maps.put("msg", "系统出了小差,请稍等...");
            }
        }else {
        	maps.put("code", 0);
        }
        return maps;
    }
    
    /**
     * 
     * 描述:
     * @author wanghaoyu
     * @version 1.0
     * @param request request请求
     * @return ModelAndView
     * @exception Nothing
     * @since 1.8
     *
     */
    @Operation(name="注销")
    @RequestMapping("/logout")
    public ModelAndView logout(HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        //获取shiro中的用户
        Subject subject = SecurityUtils.getSubject();
        //获取用户账号信息
        String account = (String) subject.getPrincipal();
        if(account != null) {
            //登出
            subject.logout();
            //同时删除session中的用户信息
            request.getSession().removeAttribute("user");
            request.getSession().invalidate();
        }
        //重定向到登陆页面
        view.setViewName("redirect:/pages/login.jsp");
        return view;
    }
    
    
    
    
}

Role management control layer:

/**
 * 
 * @author yy
 *
 */
@Controller
@RequestMapping("/role")
public class RoleController {

	Logger logger = LoggerFactory.getLogger(RoleController.class);

	@Autowired
	IRoleService roleService;

	@Autowired
	IRolePermissionService rolePermissionService;
	
	@Autowired
	IPermissionService permissionService;
	
	@Autowired
	RedisUtil redisUtil;

	/**
	 * 
	 * 描述:分页加条件查询Role
	 * 
	 * @author wanghaoyu
	 * @version 1.0
	 * @param page
	 * @param limit
	 * @param role
	 * @return Map<String,Object>
	 * @exception Nothing
	 * @since 1.8
	 *
	 */
	@Operation(name = "查询职位")
	@RequiresPermissions("4001")
	@RequestMapping("/findRoles")
	@ResponseBody
	public Map<String, Object> findRoles(Integer page, Integer limit, Role role) {
		Map<String, Object> map = new HashMap<String, Object>(16);

		// 创建角色模板类
		RoleExample roleExample = new RoleExample();
		// 创建查询准则
		Criteria criteria = roleExample.createCriteria();
		// 判断role中的条件
		if (role.getName() != null) {
			criteria.andNameLike("%" + role.getName() + "%");
		}
		// 分页数据合法性判断
		if (page == null || page <= 0) {
			page = 1;
		}
		if (limit == null || limit <= 0) {
			limit = 10;
		}
		// 偏移值,即从第几条数据开始查
		Long offset = new Long((page - 1) * limit);
		// 数据总条数
		Long count = roleService.countByRoleExample(roleExample);

		roleExample.setOffset(offset);
		roleExample.setLimit(limit);

		List<Role> roles = roleService.selectByRoleExample(roleExample);

		logger.info(roles.toString());

		// 封装数据,返回到前台
		map.put("data", roles);
		map.put("code", 0);
		map.put("msg", "success");
		map.put("count", count);
		return map;
	}

	/**
	 * 
	 * 描述:根据职位编号删除职位
	 * 
	 * @author wanghaoyu
	 * @version 1.0
	 * @param id
	 * @return Map<String,Object>
	 * @exception Nothing
	 * @since 1.8
	 *
	 */
	@Operation(name = "删除职位")
	@RequiresPermissions("4004")
	@RequestMapping("/deleteRole")
	@ResponseBody
	public Map<String, Object> deleteRole(Integer id) {
		Map<String, Object> map = new HashMap<String, Object>(16);
		// 用于判断返回给前台的结果
		boolean success = false;
		// 删除结果判断
		if (roleService.deleteRoleByPrimaryKey(id)) {
			success = true;
		}
		map.put("success", success);
		map.put("code", 0);
		return map;
	}

	/**
	 * 
	 * 描述:编辑职位
	 * 
	 * @author wanghaoyu
	 * @version 1.0
	 * @param role
	 * @return Map<String,Object>
	 * @exception Nothing
	 * @since 1.8
	 *
	 */
	@Operation(name = "编辑职位")
	@RequiresPermissions("4002")
	@RequestMapping("/editRole")
	@ResponseBody
	public Map<String, Object> editRole(Role role) {
		Map<String, Object> map = new HashMap<String, Object>(16);
		// 用于判断返回给前台的结果
		boolean success = false;
		if (roleService.updateRoleByPrimaryKey(role)) {
			success = true;
		}
		map.put("success", success);
		map.put("code", 0);
		return map;
	}

	/**
	 * 
	 * 描述:添加职位
	 * 
	 * @author wanghaoyu
	 * @version 1.0
	 * @param role
	 * @return Map<String,Object>
	 * @exception Nothing
	 * @since 1.8
	 *
	 */
	@Operation(name = "添加职位")
	@RequiresPermissions("4003")
	@RequestMapping("/addRole")
	@ResponseBody
	public Map<String, Object> addRole(Role role) {
		Map<String, Object> map = new HashMap<String, Object>(16);
		// 用于判断返回给前台的结果
		boolean success = false;
		if (roleService.insertRole(role)) {
			success = true;
		}
		map.put("success", success);
		map.put("code", 0);
		return map;
	}

	/**
	 * 
	 * 描述:查询角色所拥有的权限id
	 * 
	 * @author huangqingwen
	 * @version 1.0
	 * @param rolePermission
	 * @return Map<String,Object>
	 * @exception Nothing
	 * @since 1.8
	 *
	 */
	@Operation(name = "查询角色所拥有的权限id")
	@RequiresAuthentication
	@RequestMapping("/findRolePermissionId")
	@ResponseBody
	public Map<String, Object> findRolePermissionId(RolePermission rolePermission) {

		Map<String, Object> maps = new HashMap<String, Object>(16);

		// 1. 获取该角色id下的所有权限id
		RolePermissionExample example = new RolePermissionExample();
		example.createCriteria().andRoleIdEqualTo(rolePermission.getRoleId());
		List<RolePermission> list = rolePermissionService.selectByRolePermissionExample(example);
		maps.put("result", list);
		return maps;
	}

	/**
	 * 
	 * 描述:分配权限给特定的角色
	 * 
	 * @author huangqingwen
	 * @version 1.0
	 * @param permissionId,
	 *            roleId
	 * @return Map<String,Object>
	 * @exception Nothing
	 * @since 1.8
	 *
	 */
	@Operation(name = "分配权限")
	@RequiresPermissions("4005")
	@RequestMapping("allotPermission")
	@ResponseBody
	public Map<String, Object> allotPermission(HttpServletRequest request, @RequestParam(value = "permissionIds[]", defaultValue="") Integer[] permissionIds,
			@RequestParam(value = "roleId") Integer roleId) {

		Map<String, Object> maps = new HashMap<String, Object>(16);

		//从session中获取用户角色
        //User user = (User)request.getSession().getAttribute("user");
		
		int result = rolePermissionService.allotPermission(permissionIds, roleId);
		
		//权限发生改变,删除权限相关的缓存
		//删除相应角色菜单的缓存
		redisUtil.remove("roleMenu-"+roleId);
		//删除权限相关的缓存
		redisUtil.remove("rolePermission-"+roleId);

		
		if (permissionIds.length > 0) {
			if (result == permissionIds.length) {
				maps.put("code", 0);
			} else {
				maps.put("code", 200);
				maps.put("msg", "分配失败!");
				return maps;
			}
		}
		maps.put("code", 0);
		return maps;
	}
	
	/**
	 * 
	 * 描述:获取用户角色的权限菜单
	 * 
	 * @author huangqingwen
	 * @version 1.0
	 * @param request
	 * @return Map<String,Object>
	 * @exception Nothing
	 * @since 1.8
	 *
	 */
	@SuppressWarnings("unchecked")
    @Operation(name="获取用户角色的权限菜单")
	@RequiresAuthentication
	@RequestMapping("/getRolePermissionMenu")
	@ResponseBody
	public Map<String, Object> getRolePermissionMenu(HttpServletRequest request){
		
		Map<String, Object> maps = new HashMap<String, Object>(16);
		
		//从session中获取用户角色
		User user = (User)request.getSession().getAttribute("user");
		
		List<Permission> userPermissions = null;
		
		logger.info(user.toString());
		
	    //先从redis缓存中查找角色权限菜单
		String roleMenu = "roleMenu-";
		if(redisUtil.exists(roleMenu+user.getRoleId())) {
		    userPermissions = (List<Permission>) redisUtil.get("roleMenu-"+user.getRoleId());
		}else {	  
		    //如果没有在缓存中找到,则从数据库中查找
		    //获取权限树
	        List<Permission> permissions = permissionService.selectTreePermission();
	        
	        //查询该用户的角色所拥有的权限id
	        RolePermissionExample rolePermissionExample = new RolePermissionExample();
	        rolePermissionExample.createCriteria().andRoleIdEqualTo(user.getRoleId());
	        List<RolePermission> rolePermissions = rolePermissionService.selectByRolePermissionExample(rolePermissionExample);
	        
	        //将用户的权限id放到数组中
	        int size = rolePermissions.size();
	        Integer[] array = new Integer[size];
	        for(int i = 0 ; i < size ; i ++ ) {
	            array[i] = rolePermissions.get(i).getPermissionId();
	        }
	        
	        //过滤用户的权限
	        userPermissions = getUserPermission(permissions, array);
	        
	        //把查找到的数据存入到redis缓存中
	        redisUtil.set("roleMenu-"+user.getRoleId(), userPermissions, 1800L);
		}
		
		maps.put("permission", userPermissions);
		maps.put("code", 0);
		return maps;
	}
	
	
	/**
     * 过滤用户的菜单
     * @param permissions
     * @param array
     * @return
     * @author huangqingwen
     */
    public List<Permission> getUserPermission(List<Permission> permissions, Integer[] array){
    	if(permissions == null) {
    		return null;
    	}
    
    	for(int i=permissions.size()-1; i>=0; i--) {
    		Permission permission = permissions.get(i);
    		boolean flag = false;
    		for (Integer a : array) {
				if(permission.getId().equals(a)) {
					flag = true;
					permission.setChildPermission(getUserPermission(permission.getChildPermission(), array));
				}
			}
    		//把类型为功能的permission也移除掉
    		if(flag == false || permission.getType().equals(1)) { 
    			permissions.remove(i);
    		}
    	}
    	
    	return permissions;
    }
}

Get the source code: Download it from "Resources" on the homepage of the blog! 

Guess you like

Origin blog.csdn.net/yuyecsdn/article/details/124208101