发表于: 2020-08-14 23:22:36

1 1209


修改拦截器

public class LoginInterceptors extends HandlerInterceptorAdapter {
    @Autowired
    UserService userService;
    private static final Logger log= LogManager.getLogger(UserController.class);
    /**
     *    在业务处理器处理请求之前被调用,返回true or false,true继续执行,false请求结束
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //请求cookie里的信息,放入cookies
        log.info("interceptor start");
        Cookie[] cookies = request.getCookies();
        //判断cookies不为空,且至少有一个cookie。
        if(cookies!=null&&cookies.length>0){
            //遍历数据库查找token
            for (Cookie cookie:cookies) {
                log.info("cookie start");
                //判读数据库是否储存了token
                if("token".equals(cookie.getName())){
                    log.info("token".equals(cookie.getName()));
                    DesUtil desUtil = new DesUtil();
                    String token = desUtil.decrypt(cookie.getValue());
                    long id = Long.valueOf(token);
                    if(userService.selectById(id)!=null){
                        log.info("success");
                        return true;
                    }else{
                        //重新定位到登录界面
                        response.sendRedirect("/a/login/0");
                        log.info("no data in database");
                        return false;
                    }
                }
            }
            response.sendRedirect("/a/login/0");
            return false;
        }
        else{
            response.sendRedirect("/a/register");
            log.info("no token please register");
            return false;
        }
    }
    /**
     * 在业务处理器处理请求完成之后,生成视图之前执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception{
        if(modelAndView != null){
            Map<String, String> map = new HashMap<String, String>();
            modelAndView.addAllObjects(map);
        }
    }
    /**
     * 在DispatcherServlet完全处理完请求之后被调用,可用于清理资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{
    }
}

修改controller

@Controller
public class UserController {
    @Autowired
    UserService userService;
    private static final Logger log = LogManager.getLogger(UserController.class);
    /**
     * 注册模块
     *
     * @return
     */
    @RequestMapping(value = "/a/register/0", method = RequestMethod.GET)
    public String registered() {
        return "register";
    }
    /**
     * 登录模块
     *
     * @return
     */
    @RequestMapping(value = "/a/login/0")
    public String login() {
        return "login";
    }
    /**
     * 注册检测模块
     *
     * @param user
     * @param name
     * @return
     */
    @RequestMapping(value = "/a/register/1")
    public String insert(User user, String name) {
        log.info("新注册用户信息================" + user);
        // 通过用户名查找数据,看是否有这条数据
        List<User> users = userService.selectByName(name);
        log.info("查看数据库里是否有配置的数据================" + users);
        // 能查出来这条数据就说明数据库里有这条数据,那么注册失败,否则注册成功,跳转到登录页面
        if (!CollectionUtils.isEmpty(users)) {
            log.info("用户已存在=============");
            return "redirect:/a/login/0";
        } else {
            if (
                    user.getName() != null
                            && user.getName().length() > 0
                            && user.getPassword() != null
                            && user.getPassword().length() > 0) {
                log.info("注册用户的信息=============" + user);
                int row = userService.insert(user);
                log.info("插入成功===============" + row);
                return "login";
            } else {
                return "redirect:/a/register/0";
            }
        }
    }
    /**
     * 登录检测模块
     *
     * @param user
     * @param name
     * @param password
     * @param response
     * @return
     */
    @RequestMapping(value = "/a/login/1", method = RequestMethod.GET)
    public String checkLogin(User user, String name, String password, HttpServletResponse response) {
        log.info("user============" + user);
        // 如果能查出来数据,说明数据库里有这条数据,那么登录成功,跳转首页,否则登录失败,跳回登录页面
        List<User> list = userService.selectByCondition(name, password);
        log.info("list=======================" + list.size());
        log.info(CollectionUtils.isEmpty(list));
        if (!CollectionUtils.isEmpty(list)) {
            Long id = user.getId();
            String token = id + "/" + System.currentTimeMillis();
            try {
                DesUtil desUtil = new DesUtil();
                token = desUtil.encrypt(token);
                //创建cookie对象
                Cookie cookie = new Cookie("token", token);
                //设置cookie登录周期,单位秒,这里就是30分钟,
                // 这里注释掉是默认周期为-1,就是每次退出页面自动清除cookie,方便测试
                // cookie.setMaxAge(30 * 60);
                //指定cookie的路径,客户端将cookie返回到该目录下
                cookie.setPath("/");
                //保存cookie到客户端
                response.addCookie(cookie);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "redirect:/a/u/profession";
        } else {
            return "redirect:/a/login/0";
        }
    }
    /**
     * 注销当前账号模块
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String loginOut(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        //这里就是把cookie中的所有数据都来出来比对
        for (Cookie cookie : cookies) {
            //当我们找到了要注销的账号的信息,就把这个账号的信息进行修改
            if ("token".equals(cookie.getName())) {
                //token的值设为null
                cookie = new Cookie("token", null);
                //将cookie时间设置为0
                cookie.setMaxAge(0);
                cookie.setPath("/");
                //然后把这个cookie加到所有的cookie中存储
                response.addCookie(cookie);
                //重定向到登录页面
                return "redirect:/login/0";
            }
        }
        //重定向到登录页面
        return "redirect:/login/0";

今日问题 暂无


返回列表 返回列表
评论

    分享到