您的位置:首页 > 编程语言 > Java开发

struts2与cookie实现自动登录

2014-02-10 14:36 92 查看


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

struts2与cookie结合时要注意采用.action 动作的方式实现cookie的读取。好了直接看代码:

首先是struts2的配置文件:struts.xml

该配置文件,用户验证成功跳转到success.jsp页面。验证失败跳转到Login.jsp页面

项目下载地址:http://download.csdn.net/source/3477755

[html] view
plaincopy

<span style="font-size:24px;"><?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></span>

接着是action文件,LoginAction.java

[java] view
plaincopy

<span style="font-size:18px;">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;

}

}

</span>

接下来是cookie工具类,主要是cookie的添加、删除与查询。CookieUtils.java

[java] view
plaincopy

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

[java] view
plaincopy

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

[html] view
plaincopy

<span style="font-size:18px;"><%@ 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>

</span>

接着是index.jsp页面

[html] view
plaincopy

<%@ 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

[html] view
plaincopy

<%@ 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>

项目下载地址:http://download.csdn.net/source/3477755
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: