Java-使用Cookie实现登陆会话保持与注销功能

1.我们就来利用Cookie实现一个简单的会话保持与注销功能!首先看看普通的登录方法(真的是普通的不能再普通…)

  @RequestMapping("login")
    public String login(User user, Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String loginname = user.getLoginname();
        String password = user.getPassword();
        Cookie cookie1 = new Cookie("loginname",loginname);
//        Cookie cookie1 = new Cookie("name", URLEncoder.encode("哈哈", "UTF-8"));//存中文信息的时候需要这样设置编码
        if (loginname!=null||password!=null){
            Map map = loginService.login(loginname, password);
        if (map.get("status").equals("200")) {
            cookie1.setMaxAge(60*60);//这里设置设置有效时间,单位的秒,我这里是一小时
            cookie1.setPath("/");//这里是之根目录下所有的目录都可以共享Cookie
            response.addCookie(cookie1);//添加Cookie
            return "system/index.jsp";
        } else {
            model.addAttribute("error", map.get("msg"));
            return "login.jsp";
        }
        }else {
            model.addAttribute("error","请输入账号密码");
            return "login.jsp";
        }

2.然后在你的拦截器里做一些判断就行~

package com.sixmai.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    //之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
      Cookie[] cookies = request.getCookies();//这里是取出Cookie
        if ((cookies!=null)){//判断Cookie是否为空
            for (Cookie cookie : cookies){//遍历Cookie判断有没有对应的name
                if (cookie.getName().equals("loginname")){//有就直接return true
                      return true;
                }
            }
        }
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

3.注销:很简单,当你点击注销的时候清除Cookie并跳转到登陆页面就行拉~

   @RequestMapping("logout")
    public String logout(HttpSession session,HttpServletRequest request,HttpServletResponse response){
//        session.removeAttribute("loginname"); 消耗session

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie :cookies){//遍历所有Cookie
            if(cookie.getName().equals("loginname")){//找到对应的cookie
                cookie.setMaxAge(0);//Cookie并不能根本意义上删除,只需要这样设置为0即可
                cookie.setPath("/");//很关键,设置成跟写入cookies一样的,全路径共享Cookie
                response.addCookie(cookie);//重新响应
                return "login.jsp";
            }
        }
        return "login.jsp";
    }

这样写了以后当你点击注销就可以直接“清除”Cookie并且跳转到登陆页面啦!

你可能感兴趣的:(cookie)