博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
struts2与cookie实现自动登录
阅读量:4986 次
发布时间:2019-06-12

本文共 7107 字,大约阅读时间需要 23 分钟。

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

struts2与cookie结合时要注意采用.action 动作的方式实现cookie的读取。好了直接看代码:
首先是struts2的配置文件:struts.xml
该配置文件,用户验证成功跳转到success.jsp页面。验证失败跳转到Login.jsp页面
项目下载地址:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name="struts.i18n.encoding" value="GBK" /> <package name="user" namespace="/user" extends="struts-default"> <!-- 用户登录 --> <action name="login" class="cn.edu.pdsu.action.LoginAction"> <result name="success" type="redirect">/success.jsp</result> <result name="login">/login.jsp </result> </action> </package> </struts>
接着是action文件,LoginAction.java
package cn.edu.pdsu.action; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import cn.edu.pdsu.bean.User; import cn.edu.pdsu.dao.UserDao; import cn.edu.pdsu.utils.CookieUtils; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware { private static final long serialVersionUID = 6650955874307814247L; public static final String USER_SESSION = "user.session"; private HttpServletResponse response; private HttpServletRequest request; private Map<String, Object> session; private CookieUtils cookieUtils = new CookieUtils(); private UserDao userDao = new UserDao(); private String username; private String password; private boolean userCookie; // 用户登录跳转 public String login() { if (cookieUtils.getCookie(request, userDao)) { return SUCCESS; } else return "login"; } @Override // 正常登录 public String execute() throws Exception { System.out.println(username + "\t" + password + "\t" + userCookie); String username = getUsername().trim(); if (username != null && !"".equals(username) && password != null && !"".equals(password)) { User user = userDao.checkUser(username, password); System.out.println(user); if (user != null) { // 判断是否要添加到cookie中 if (userCookie) { Cookie cookie = cookieUtils.addCookie(user); response.addCookie(cookie);// 添加cookie到response中 } // 2.将user 设置到session中 session.put(USER_SESSION, user); return SUCCESS; } } this.addFieldError("username", "用户名或密码错误!"); return "login"; } // 用户退出 public String logout() { HttpSession session = request.getSession(false); if (session != null) session.removeAttribute(USER_SESSION); Cookie cookie = cookieUtils.delCookie(request); if (cookie != null) response.addCookie(cookie); return "login"; } public boolean getUserCookie() { return userCookie; } public void setUserCookie(boolean userCookie) { this.userCookie = userCookie; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setServletResponse(HttpServletResponse response) { this.response = response; } public void setSession(Map<String, Object> session) { this.session = session; } public void setServletRequest(HttpServletRequest request) { this.request = request; } }
接下来是cookie工具类,主要是cookie的添加、删除与查询。CookieUtils.java
package cn.edu.pdsu.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import cn.edu.pdsu.action.LoginAction; import cn.edu.pdsu.bean.User; import cn.edu.pdsu.dao.UserDao; /** * cookie的增加、删除、查询 */ public class CookieUtils { public static final String USER_COOKIE = "user.cookie"; // 添加一个cookie public Cookie addCookie(User user) { Cookie cookie = new Cookie(USER_COOKIE, user.getUsername() + "," + user.getPassword()); System.out.println("添加cookie"); cookie.setMaxAge(60 * 60 * 24 * 14);// cookie保存两周 return cookie; } // 得到cookie public boolean getCookie(HttpServletRequest request, UserDao userDAO) { Cookie[] cookies = request.getCookies(); System.out.println("cookies: " + cookies); if (cookies != null) { for (Cookie cookie : cookies) { System.out.println("cookie: " + cookie.getName()); if (CookieUtils.USER_COOKIE.equals(cookie.getName())) { String value = cookie.getValue(); if (StringUtils.isNotBlank(value)) { String[] split = value.split(","); String username = split[0]; String password = split[1]; User user = userDAO.checkUser(username, password); if (user != null) { HttpSession session = request.getSession(); session.setAttribute(LoginAction.USER_SESSION, user);// 添加用户到session中 return true; } } } } } return false; } // 删除cookie public Cookie delCookie(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (USER_COOKIE.equals(cookie.getName())) { cookie.setValue(""); cookie.setMaxAge(0); return cookie; } } } return null; } }
接着上的是用户信息验证类,UserDao.java
package cn.edu.pdsu.dao; import cn.edu.pdsu.bean.User; /** * 用户的有效性校验 */ public class UserDao { // 模拟查找用户 public User checkUser(String username, String password) { if (username.equals("hello") && password.equals("123")) { User user = new User(); user.setUsername("hello"); user.setPassword("123"); return user; } return null; } } 接着就是用户登录页面,login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%@taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>登录页面</title> </head> <body> <center> <s:form action="login" namespace="/user" method="post"> <s:textfield label="用户名" name="username"></s:textfield> <s:password label="密码" name="password"></s:password> <s:checkbox label="自动登录" name="userCookie" value="true"></s:checkbox> <s:submit value="提交"></s:submit> </s:form> </center> </body> </html>
接着是index.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; response.sendRedirect(basePath+"user/login!login.action"); %>
登录成功页面success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%@taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>登录成功!</title> </head> <body> <h1>欢迎您的到来!</h1><br> <s:a action="login!logout.action" namespace="/user"> 安全退出</s:a> </body> </html>
项目下载地址:

转载于:https://www.cnblogs.com/hibernate3-example/archive/2011/07/29/2492715.html

你可能感兴趣的文章
关于android4.3 bluetooth4.0的那些事儿
查看>>
嵌入式成长轨迹14 【嵌入式环境及基础】【Linux下的C编程 上】【gcc、gdb和GNU Make】...
查看>>
C语言讲义——变量的输出
查看>>
shell脚本 ----每天学一点shell
查看>>
FZU2150 :Fire Game (双起点BFS)
查看>>
php_常用操作_读取文件_数据库操作
查看>>
Linux中GCC源码编译安装
查看>>
equals与==关于Object覆盖和重载问题
查看>>
KVO
查看>>
js基础教程四之无缝滚动
查看>>
关于C51 keil使用中.c文件的链接心得
查看>>
Ios 弹框 MJPopup,KxMenu
查看>>
ssh框架添加时添加不到数据库问题
查看>>
解决AR中Receivable Activities 运行不了的问题
查看>>
SQL SERVER 如何处理带字母的自增列--【叶子】
查看>>
使用DocFX生成文档
查看>>
AssemblyInfo.cs文件的作用
查看>>
android之PackageManager简单介绍
查看>>
GitLab备份与恢复
查看>>
20155307《网络对抗》免杀原理与实践
查看>>