struts2与cookie实现自动登录

一、本文主要介绍struts2与cookie结合实现自动登录

struts2与cookie结合时要注意采用.action 动作的方式实现cookie的读取。好了直接看代码:
首先是struts2的配置文件:struts.xml
该配置文件,用户验证成功跳转到success.jsp页面。验证失败跳转到Login.jsp页面
[html]  view plain copy
 
  1. <span style="font-size:24px;"><?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">  
  3. <struts>  
  4.     <constant name="struts.i18n.encoding" value="GBK" />  
  5.     <package name="user" namespace="/user" extends="struts-default">  
  6.         <!-- 用户登录 -->  
  7.         <action name="login" class="cn.edu.pdsu.action.LoginAction">  
  8.             <result name="success" type="redirect">/success.jsp</result>  
  9.             <result name="login">/login.jsp </result>  
  10.         </action>  
  11.     </package>  
  12. </struts></span>  


接着是action文件,LoginAction.java

[java]  view plain copy
 
  1. <span style="font-size:18px;">package cn.edu.pdsu.action;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import javax.servlet.http.Cookie;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8. import javax.servlet.http.HttpSession;  
  9.   
  10. import org.apache.struts2.interceptor.ServletRequestAware;  
  11. import org.apache.struts2.interceptor.ServletResponseAware;  
  12. import org.apache.struts2.interceptor.SessionAware;  
  13.   
  14. import cn.edu.pdsu.bean.User;  
  15. import cn.edu.pdsu.dao.UserDao;  
  16. import cn.edu.pdsu.utils.CookieUtils;  
  17.   
  18. import com.opensymphony.xwork2.ActionSupport;  
  19.   
  20. public class LoginAction extends ActionSupport implements ServletRequestAware,  
  21.         ServletResponseAware, SessionAware {  
  22.     private static final long serialVersionUID = 6650955874307814247L;  
  23.     public static final String USER_SESSION = "user.session";  
  24.     private HttpServletResponse response;  
  25.     private HttpServletRequest request;  
  26.     private Map<String, Object> session;  
  27.     private CookieUtils cookieUtils = new CookieUtils();  
  28.     private UserDao userDao = new UserDao();  
  29.     private String username;  
  30.     private String password;  
  31.     private boolean userCookie;  
  32.   
  33.     // 用户登录跳转  
  34.     public String login() {  
  35.         if (cookieUtils.getCookie(request, userDao)) {  
  36.             return SUCCESS;  
  37.         } else  
  38.             return "login";  
  39.     }  
  40.   
  41.     @Override  
  42.     // 正常登录  
  43.     public String execute() throws Exception {  
  44.         System.out.println(username + "\t" + password + "\t" + userCookie);  
  45.         String username = getUsername().trim();  
  46.         if (username != null && !"".equals(username) && password != null  
  47.                 && !"".equals(password)) {  
  48.             User user = userDao.checkUser(username, password);  
  49.             System.out.println(user);  
  50.             if (user != null) {  
  51.                 // 判断是否要添加到cookie中  
  52.                 if (userCookie) {  
  53.                     Cookie cookie = cookieUtils.addCookie(user);  
  54.                     response.addCookie(cookie);// 添加cookie到response中  
  55.                 }  
  56.                 // 2.将user 设置到session中  
  57.                 session.put(USER_SESSION, user);  
  58.                 return SUCCESS;  
  59.             }  
  60.         }  
  61.         this.addFieldError("username""用户名或密码错误!");  
  62.         return "login";  
  63.     }  
  64.   
  65.     // 用户退出  
  66.     public String logout() {  
  67.         HttpSession session = request.getSession(false);  
  68.         if (session != null)  
  69.             session.removeAttribute(USER_SESSION);  
  70.         Cookie cookie = cookieUtils.delCookie(request);  
  71.         if (cookie != null)  
  72.             response.addCookie(cookie);  
  73.         return "login";  
  74.     }  
  75.   
  76.     public boolean getUserCookie() {  
  77.         return userCookie;  
  78.     }  
  79.   
  80.     public void setUserCookie(boolean userCookie) {  
  81.         this.userCookie = userCookie;  
  82.     }  
  83.   
  84.     public String getUsername() {  
  85.         return username;  
  86.     }  
  87.   
  88.     public void setUsername(String username) {  
  89.         this.username = username;  
  90.     }  
  91.   
  92.     public String getPassword() {  
  93.         return password;  
  94.     }  
  95.   
  96.     public void setPassword(String password) {  
  97.         this.password = password;  
  98.     }  
  99.   
  100.     public void setServletResponse(HttpServletResponse response) {  
  101.         this.response = response;  
  102.     }  
  103.   
  104.     public void setSession(Map<String, Object> session) {  
  105.         this.session = session;  
  106.     }  
  107.   
  108.     public void setServletRequest(HttpServletRequest request) {  
  109.         this.request = request;  
  110.     }  
  111.   
  112. }  
  113. </span>  
接下来是cookie工具类,主要是cookie的添加、删除与查询。CookieUtils.java
[java]  view plain copy
 
  1. package cn.edu.pdsu.utils;  
  2.   
  3. import javax.servlet.http.Cookie;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpSession;  
  6.   
  7. import org.apache.commons.lang.StringUtils;  
  8.   
  9. import cn.edu.pdsu.action.LoginAction;  
  10. import cn.edu.pdsu.bean.User;  
  11. import cn.edu.pdsu.dao.UserDao;  
  12.   
  13. /** 
  14.  * cookie的增加、删除、查询 
  15.  */  
  16. public class CookieUtils {  
  17.     public static final String USER_COOKIE = "user.cookie";  
  18.   
  19.     // 添加一个cookie  
  20.     public Cookie addCookie(User user) {  
  21.         Cookie cookie = new Cookie(USER_COOKIE, user.getUsername() + ","  
  22.                 + user.getPassword());  
  23.         System.out.println("添加cookie");  
  24.         cookie.setMaxAge(60 * 60 * 24 * 14);// cookie保存两周  
  25.         return cookie;  
  26.     }  
  27.   
  28.     // 得到cookie  
  29.     public boolean getCookie(HttpServletRequest request, UserDao userDAO) {  
  30.         Cookie[] cookies = request.getCookies();  
  31.         System.out.println("cookies: " + cookies);  
  32.         if (cookies != null) {  
  33.             for (Cookie cookie : cookies) {  
  34.                 System.out.println("cookie: " + cookie.getName());  
  35.                 if (CookieUtils.USER_COOKIE.equals(cookie.getName())) {  
  36.                     String value = cookie.getValue();  
  37.                     if (StringUtils.isNotBlank(value)) {  
  38.                         String[] split = value.split(",");  
  39.                         String username = split[0];  
  40.                         String password = split[1];  
  41.                         User user = userDAO.checkUser(username, password);  
  42.                         if (user != null) {  
  43.                             HttpSession session = request.getSession();  
  44.                             session.setAttribute(LoginAction.USER_SESSION, user);// 添加用户到session中  
  45.                             return true;  
  46.                         }  
  47.                     }  
  48.                 }  
  49.             }  
  50.         }  
  51.         return false;  
  52.     }  
  53.   
  54.     // 删除cookie  
  55.     public Cookie delCookie(HttpServletRequest request) {  
  56.         Cookie[] cookies = request.getCookies();  
  57.         if (cookies != null) {  
  58.             for (Cookie cookie : cookies) {  
  59.                 if (USER_COOKIE.equals(cookie.getName())) {  
  60.                     cookie.setValue("");  
  61.                     cookie.setMaxAge(0);  
  62.                     return cookie;  
  63.                 }  
  64.             }  
  65.         }  
  66.         return null;  
  67.     }  
  68. }  

接着上的是用户信息验证类,UserDao.java
[java]  view plain copy
 
  1. package cn.edu.pdsu.dao;  
  2.   
  3. import cn.edu.pdsu.bean.User;  
  4.   
  5. /** 
  6.  * 用户的有效性校验 
  7.  */  
  8. public class UserDao {  
  9.   
  10.     // 模拟查找用户  
  11.     public User checkUser(String username, String password) {  
  12.         if (username.equals("hello") && password.equals("123")) {  
  13.             User user = new User();  
  14.             user.setUsername("hello");  
  15.             user.setPassword("123");  
  16.             return user;  
  17.         }  
  18.         return null;  
  19.     }  
  20.   
  21. }  
接着就是用户登录页面,login.jsp

[html]  view plain copy
 
  1. <span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>  
  2. <%@taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.     <title>登录页面</title>  
  13.   </head>  
  14.   <body>  
  15.    <center>  
  16.    <s:form action="login" namespace="/user" method="post">  
  17.    <s:textfield label="用户名" name="username"></s:textfield>  
  18.    <s:password label="密码" name="password"></s:password>  
  19.    <s:checkbox label="自动登录" name="userCookie" value="true"></s:checkbox>  
  20.    <s:submit value="提交"></s:submit>  
  21.    </s:form>  
  22.    </center>  
  23.   </body>  
  24. </html>  
  25. </span>  
接着是index.jsp页面
[html]  view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. response.sendRedirect(basePath+"user/login!login.action");  
  6. %>  

登录成功页面success.jsp
[html]  view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>  
  2. <%@taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.     <title>登录成功!</title>  
  12.   </head>  
  13.   <body>  
  14.     <h1>欢迎您的到来!</h1><br>  
  15.     <s:a action="login!logout.action" namespace="/user"> 安全退出</s:a>  
  16.   </body>  
  17. </html>  

猜你喜欢

转载自zhitangrui2010.iteye.com/blog/2217937