栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaWeb使用Session和Cookie实现登录认证

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaWeb使用Session和Cookie实现登录认证

后台管理页面往往需要登录才可以进行操作,这时就需要Seession来记录登录状态

要实现起来也是非常简单,只需要自定义一个HandlerInterceptor就行了

自定义的HandlerInterceptor也只有短短几行代码

public class LoginInterceptor implements HandlerInterceptor {

  @Override
  public void afterCompletion(HttpServletRequest request,
  HttpServletResponse response, Object obj, Exception err)
      throws Exception {
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object obj, ModelAndView mav) throws Exception {

  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
 Object obj) throws Exception {
    //获取session里的登录状态值
    String str = (String) request.getSession().getAttribute("isLogin");
    //如果登录状态不为空则返回true,返回true则会执行相应controller的方法
    if(str!=null){
      return true;
    }
    //如果登录状态为空则重定向到登录页面,并返回false,不执行原来controller的方法
    response.sendRedirect("/backend/loginPage");
    return false;
  }
}

Controller代码

@Controller
@RequestMapping("/backend")
public class BackendController {

  @RequestMapping(value = "/loginPage", method = {RequestMethod.GET})
  public String loginPage(HttpServletRequest request,String account, String password){
    return "login";
  }

  @RequestMapping(value = "/login", method = {RequestMethod.POST})
  public String login(HttpServletRequest request,RedirectAttributes model, String account, String password){
    //验证账号密码,如果符合则改变session里的状态,并重定向到主页
    if ("jack".equals(account)&&"jack2017".equals(password)){
      request.getSession().setAttribute("isLogin","yes");
      return "redirect:IndexPage";
    }else {
      //密码错误则重定向回登录页,并返回错误,因为是重定向所要要用到RedirectAttributes
      model.addFlashAttribute("error","密码错误");
      return "redirect:loginPage";
    }
  }
  //登出,移除登录状态并重定向的登录页
  @RequestMapping(value = "/loginOut", method = {RequestMethod.GET})
  public String loginOut(HttpServletRequest request) {
    request.getSession().removeAttribute("isLogin");
    return "redirect:loginPage";
  }
  @RequestMapping(value = "/IndexPage", method = {RequestMethod.GET})
  public String IndexPage(HttpServletRequest request){
    return "Index";
  }

}

spring的配置

  

  
  
    
    
      
      
      
      
      
      
    
  

一个简单的Session实现登录认证系统就这样完成了,如果想登录状态退出浏览器后仍保留一段时间的可以将Session改为cookie

一般情况下我们都会使用cookie

cookie和Session的方法差不多

使用cookie的自定义HandlerInterceptor

public class LoginInterceptor implements HandlerInterceptor {

  @Override
  public void afterCompletion(HttpServletRequest request,
  HttpServletResponse response, Object obj, Exception err)
      throws Exception {
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object obj, ModelAndView mav) throws Exception {

  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
 Object obj) throws Exception {
//    获取request的cookie
    cookie[] cookies = request.getcookies();
    if (null==cookies) {
      System.out.println("没有cookie==============");
    } else {
//      遍历cookie如果找到登录状态则返回true执行原来controller的方法
      for(cookie cookie : cookies){
 if(cookie.getName().equals("isLogin")){
   return true;
 }
      }
    }
//    没有找到登录状态则重定向到登录页,返回false,不执行原来controller的方法
    response.sendRedirect("/backend/loginPage");
    return false;
  }
}

Controller的变化也不大

@Controller
@RequestMapping("/backend")
public class BackendController {

  @RequestMapping(value = "/loginPage", method = {RequestMethod.GET})
  public String loginPage(HttpServletRequest request, String account, String password) {
    return "login";
  }

  @RequestMapping(value = "/login", method = {RequestMethod.POST})
  public String login(HttpServletRequest request, HttpServletResponse response, RedirectAttributes model, String account, String password) {
    if ("edehou".equals(account) && "aidou2017".equals(password)) {
      cookie cookie = new cookie("isLogin", "yes");
      cookie.setMaxAge(30 * 60);// 设置为30min
      cookie.setPath("/");
      response.addcookie(cookie);
      return "redirect:IndexPage";
    } else {
      model.addFlashAttribute("error", "密码错误");
      return "redirect:loginPage";
    }
  }

  @RequestMapping(value = "/logOut", method = {RequestMethod.GET})
  public String loginOut(HttpServletRequest request, HttpServletResponse response) {
    cookie[] cookies = request.getcookies();
    for (cookie cookie : cookies) {
      if (cookie.getName().equals("isLogin")) {
 cookie.setValue(null);
 cookie.setMaxAge(0);// 立即销毁cookie
 cookie.setPath("/");
 response.addcookie(cookie);
 break;
      }
    }
    return "redirect:loginPage";
  }

  @RequestMapping(value = "/IndexPage", method = {RequestMethod.GET})
  public String IndexPage(HttpServletRequest request) {
    return "Index";
  }

}

spring的配置和之前的一模一样

注意

这里只是演示,建议在实际项目中cookie的键和值要经过特殊处理,否则会引发安全问题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/147197.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号