SpringMVC记住密码功能

2024-06-01 10:18

本文主要是介绍SpringMVC记住密码功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

CookieTool(Cookie帮助类):

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. package com.utcsoft.common.cookie;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4. import javax.servlet.http.Cookie;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. public class CookieTool {  
  9.   
  10.     /** 
  11.     * 设置cookie(接口方法) 
  12.     * @author 刘鹏 
  13.     * @param response 
  14.     * @param name  cookie名字 
  15.     * @param value cookie值 
  16.     * @param maxAge cookie生命周期  以秒为单位 
  17.     */  
  18.     public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){  
  19.         Cookie cookie = new Cookie(name,value);  
  20.         cookie.setPath("/");  
  21.         if(maxAge>0){    
  22.             cookie.setMaxAge(maxAge);  
  23.         }  
  24.         response.addCookie(cookie);  
  25.         }  
  26.       
  27.     /** 
  28.     * 根据名字获取cookie(接口方法) 
  29.     * @author 刘鹏 
  30.     * @param request 
  31.     * @param name cookie名字 
  32.     * @return 
  33.     */  
  34.     public static Cookie getCookieByName(HttpServletRequest request,String name){  
  35.         Map<String,Cookie> cookieMap = ReadCookieMap(request);  
  36.         if(cookieMap.containsKey(name)){  
  37.           Cookie cookie = (Cookie)cookieMap.get(name);  
  38.           return cookie;  
  39.         }else{  
  40.           return null;  
  41.         }   
  42.         }  
  43.       
  44.     /** 
  45.     * 将cookie封装到Map里面(非接口方法) 
  46.     * @author 刘鹏 
  47.     * @param request 
  48.     * @return 
  49.     */  
  50.     private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){   
  51.     Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();  
  52.     Cookie[] cookies = request.getCookies();  
  53.     if(null!=cookies){  
  54.       for(Cookie cookie : cookies){  
  55.        cookieMap.put(cookie.getName(), cookie);  
  56.       }  
  57.     }  
  58.     return cookieMap;  
  59.     }  
  60.       
  61.       
  62. }  

AuthorizedInterceptor(拦截器):

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. package com.utcsoft.common.interceptor;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  4. import javax.servlet.http.Cookie;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7. import org.springframework.web.servlet.HandlerInterceptor;  
  8. import org.springframework.web.servlet.ModelAndView;  
  9. import com.utcsoft.common.cookie.CookieTool;  
  10. import com.utcsoft.pcapps.selfservice.dao.UtcUsersDao;  
  11. import com.utcsoft.pcapps.selfservice.entity.UtcUsers;  
  12.   
  13. public class AuthorizedInterceptor implements HandlerInterceptor {  
  14.   
  15.     /**  
  16.      * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。该方法将在整个请求完成之后,也就是DispatcherServlet渲染了视图执行,  
  17.      * 这个方法的主要作用是用于清理资源的,当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。  
  18.      */   
  19.     public void afterCompletion(HttpServletRequest arg0,HttpServletResponse arg1, Object arg2, Exception arg3)  
  20.             throws Exception {  
  21.     }  
  22.   
  23.      /**  
  24.      * 这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之  
  25.      * 后,也就是在Controller的方法调用之后执行,但是它会在DispatcherServlet进行视图的渲染之前执行,也就是说在这个方法中你可以对ModelAndView进行操  
  26.      * 作。这个方法的链式结构跟正常访问的方向是相反的,也就是说先声明的Interceptor拦截器该方法反而会后调用,这跟Struts2里面的拦截器的执行过程有点像,  
  27.      * 只是Struts2里面的intercept方法中要手动的调用ActionInvocation的invoke方法,Struts2中调用ActionInvocation的invoke方法就是调用下一个Interceptor  
  28.      * 或者是调用action,然后要在Interceptor之前调用的内容都写在调用invoke之前,要在Interceptor之后调用的内容都写在调用invoke方法之后。  
  29.      */    
  30.     public void postHandle(HttpServletRequest request, HttpServletResponse response,Object handler, ModelAndView modelAndView) throws Exception {  
  31.     }  
  32.   
  33.      /**  
  34.      * preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用,SpringMVC中的Interceptor拦截器是链式的,可以同时存在  
  35.      * 多个Interceptor,然后SpringMVC会根据声明的前后顺序一个接一个的执行,而且所有的Interceptor中的preHandle方法都会在  
  36.      * Controller方法调用之前调用。SpringMVC的这种Interceptor链式结构也是可以进行中断的,这种中断方式是令preHandle的返  
  37.      * 回值为false,当preHandle的返回值为false的时候整个请求就结束了。  
  38.      */    
  39.     public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {  
  40.         String uri = request.getRequestURI();  
  41.         //登陆请求不拦截  
  42.         /*if(uri.indexOf("checkUser.do") != -1){ 
  43.             return true; 
  44.         }*/  
  45.          
  46.       //设置不拦截的对象  
  47.         String[] noFilters = new String[] {"logOn","index","supplier","innerChart"};  //对登录本身的页面以及业务不拦截  
  48.         boolean beFilter = true;   
  49.         for (String s : noFilters) {    
  50.             if (uri.indexOf(s) != -1) {    
  51.                 beFilter = false;    
  52.                 break;    
  53.             }    
  54.         }  
  55.           
  56.    if (beFilter==true) {//除了不拦截的对象以外  
  57.         String path = request.getContextPath();  
  58.         String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";  
  59.     /* 
  60.     注意:每次重新启动浏览器会重新启动一个sessionId和Cookie,之前设置的session会因为sessionId的变化而取不到,所以会出现用户明明已经登录,但是重开浏览器又需要登录. 
  61.         流程: 
  62.         1、用户选择记住密码:取出cookie中的用户名和密码查询,如果此用户已不存在,则清除cookie中的值,如果存在则判断用户是否重新登录,如果未重新登录则将cookie中用户信息设置到session中,如果用户重新登录了则判断登录用户是否与cookie中用户一致,一致则将cookie中用户信息设置到session中,不一致则将当前登录用户的信息设置到session中。 
  63.                 将用户信息放入session中是为了(通过cookie中的用户名密码可以得到用户信息): 
  64.                     1、重开浏览器的时候如果已经登录的用户可以直接进入 
  65.                     2、防止用户直接将执行方法的连接拷贝进地址栏,而方法中又需要在session中取用户信息的错误 
  66.         2、用户未选记住密码:判断session中是否存在用户信息,如果存在,则true,如果不存在则返回登录页面 
  67.     */  
  68.             Cookie cokLoginName = CookieTool.getCookieByName(request, "loginName");  
  69.             Cookie cokLoginPwd = CookieTool.getCookieByName(request, "loginPwd");  
  70.             //如果前面的人登录勾选了记住密码,cookie中存在上一个人的信息  
  71.             if (cokLoginName != null && cokLoginPwd != null && cokLoginName.getValue() != "" && cokLoginPwd.getValue() != "") {  
  72.                 String loginName = cokLoginName.getValue();  
  73.                 String loginPwd = cokLoginPwd.getValue();  
  74.                   
  75.                 // 检查到客户端保存了用户的密码,进行该账户的验证  
  76.                 UtcUsersDao usersDao = new UtcUsersDao();  
  77.                 UtcUsers users = usersDao.findByNameAndPwd(loginName, loginPwd);  
  78.                   
  79.                 //如果此人已经被管理员删除  
  80.                 if (users == null) {  
  81.                     CookieTool.addCookie(response, "loginName"null0); // 清除Cookie  
  82.                     CookieTool.addCookie(response, "loginPwd"null0); // 清除Cookie  
  83.                     try {  
  84.                         response.sendRedirect(basePath + "self/logOn.do");  
  85.                         return false;  
  86.                     } catch (IOException e) {  
  87.                         e.printStackTrace();  
  88.                     }  
  89.                     request.getSession().setAttribute("errorInfo""请登录!");  
  90.                 }  
  91.                 //如果存在此人  
  92.                 else {  
  93.                     UtcUsers utcUsers = (UtcUsers)request.getSession().getAttribute("utcUsers");  
  94.                     if (utcUsers==null) {//如果未登录而直接拷贝地址栏进入页面  
  95.                         request.getSession().setAttribute("utcUsers", users);  
  96.                     }else {//用户登录后  
  97.                         if (utcUsers.getUsername().equals(users.getUsername())) {//如果当前登录人与cookie中信息一致  
  98.                             request.getSession().setAttribute("utcUsers", users);  
  99.                         }else {//如果当前登录人与cookie中信息不一致  
  100.                             request.getSession().setAttribute("utcUsers", utcUsers);  
  101.                         }  
  102.                     }  
  103.                 }  
  104.             }  
  105.             //如果cookie中没有内容,即未勾选记住密码,或者是退出后清除了cookie  
  106.             else{  
  107.                 UtcUsers u = (UtcUsers)request.getSession().getAttribute("utcUsers");  
  108.                 if (u==null) {//如果未登录  
  109.                     response.sendRedirect(basePath + "self/logOn.do");  
  110.                      return false;  
  111.                 }else {//如果已经登录  
  112.                     //执行下一步  
  113.                 }  
  114.             }  
  115.               
  116.             /******退出的时候记得清除cookie中的内容,如果用户已经登录********/  
  117.           
  118.    }  
  119.         return true;  
  120.     }  
  121.   
  122. }  



 

登录验证的方法:

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * 描述:登录验证 
  3.      * @param request 
  4.      * @param response 
  5.      * @return 
  6.      * @throws IOException 
  7.      */  
  8.     @RequestMapping(value="/index")  
  9.     public String index(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws IOException{  
  10.         String user_name = httpRequest.getParameter("user_name");  
  11.         String user_pwd = httpRequest.getParameter("user_pwd");  
  12.         String str = null;  
  13.         UtcUsersDao usersDao = new UtcUsersDao();  
  14.         UtcUsers users = usersDao.findByNameAndPwd(user_name,user_pwd);  
  15.         if(users==null){//登录验证失败  
  16.             logger.info("登录失败");  
  17.             httpRequest.getSession().setAttribute("errorInfo","用户名或密码错误,请重新登录!");  
  18.             String path = httpRequest.getContextPath();  
  19.             String basePath = httpRequest.getScheme() + "://"+ httpRequest.getServerName() + ":" + httpRequest.getServerPort()+ path + "/";  
  20.             httpResponse.sendRedirect(basePath+"self/logOn.do");  
  21.         }else if ("10".equals(users.getUserrole())) {  
  22.             int  loginMaxAge = 30*24*60*60;   //定义账户密码的生命周期,这里是一个月。单位为秒  
  23.             String rememberPwd = httpRequest.getParameter("rememberPwd")==null?"":httpRequest.getParameter("rememberPwd").toString();  
  24.             if ("rememberPwd".equals(rememberPwd)) {  
  25.                 CookieTool.addCookie(httpResponse , "loginName" , user_name , loginMaxAge); //将姓名加入到cookie中  
  26.                 CookieTool.addCookie(httpResponse , "loginPwd" , user_pwd , loginMaxAge);   //将密码加入到cookie中  
  27.             }  
  28.             httpRequest.getSession().setAttribute("utcUsers", users);  
  29.             str = "/Administrator";  
  30.         }else {  
  31.             int  loginMaxAge = 30*24*60*60;   //定义账户密码的生命周期,这里是一个月。单位为秒  
  32.             String rememberPwd = httpRequest.getParameter("rememberPwd")==null?"":httpRequest.getParameter("rememberPwd").toString();  
  33.             if ("rememberPwd".equals(rememberPwd)) {  
  34.                 CookieTool.addCookie(httpResponse , "loginName" , user_name , loginMaxAge); //将姓名加入到cookie中  
  35.                 CookieTool.addCookie(httpResponse , "loginPwd" , user_pwd , loginMaxAge);   //将密码加入到cookie中  
  36.             }  
  37.             //将UtcUsers放到session中  
  38.             httpRequest.getSession().setAttribute("utcUsers", users);  
  39.             str = "self/index";  
  40.         }  
  41.         return str;  
  42.     }  

点击退出系统按钮的时候一定要记得清除cookie值()

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. /**返回登录页面的中转方法,用于清除cookie中内容,不要在登录方法中清除,因为首次登录时候进入登录方法cookie是不需要清除的 
  2.      * @author liupeng 
  3.      * @param request 
  4.      * @param response 
  5.      * @return 
  6.      * @throws UnknownHostException 
  7.      */  
  8.     @RequestMapping(value="/logOnTransit")  
  9.     public void logOnTransit(HttpServletRequest request,HttpServletResponse response) throws Exception{  
  10.         CookieTool.addCookie(response, "loginName"null0); // 清除Cookie  
  11.         CookieTool.addCookie(response, "loginPwd"null0); // 清除Cookie  
  12.           
  13.         String path = request.getContextPath();  
  14.         String basePath = request.getScheme() + "://"  
  15.                 + request.getServerName() + ":" + request.getServerPort()  
  16.                 + path + "/";  
  17.         String finalPath = basePath+"self/logOn.do";  
  18.         response.sendRedirect(finalPath);  
  19.           
  20.     }  

这篇关于SpringMVC记住密码功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1020726

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Java中的.close()举例详解

《Java中的.close()举例详解》.close()方法只适用于通过window.open()打开的弹出窗口,对于浏览器的主窗口,如果没有得到用户允许是不能关闭的,:本文主要介绍Java中的.... 目录当你遇到以下三种情况时,一定要记得使用 .close():用法作用举例如何判断代码中的 input

Spring Gateway动态路由实现方案

《SpringGateway动态路由实现方案》本文主要介绍了SpringGateway动态路由实现方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录前沿何为路由RouteDefinitionRouteLocator工作流程动态路由实现尾巴前沿S