struts2与cookie实现自动登录和验证码验证
主要介绍struts2与cookie结合实现自动登录
struts2的jar包

链接数据库文件 db.properties
dbDriver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@localhost::orcl
userName=test
password=password
dao层类代码,通过登录名获取用户信息
package com.struts.dao.impl; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import com.struts.dao.UserDao;
import com.struts.proj.User;
import com.struts.util.BeanConnection; public class UserDaoImpl implements UserDao {
private BeanConnection dbconn = new BeanConnection();
public User login(String loginname) {
Connection conn = dbconn.getConnection();
ResultSet rs = null ;
String selsql = "select * from t_scoa_sys_user where f_loginname='"+loginname+"'";
//System.out.println(selsql);
PreparedStatement pstmt = null;
User user = null;
try {
pstmt = conn.prepareStatement(selsql);
//pstmt.setString(3, loginname);
rs = pstmt.executeQuery();
while(rs.next()){
user = new User();
user.setId(rs.getLong());
user.setF_username(rs.getString());
user.setF_loginname(rs.getString());
user.setF_sex(rs.getString());
user.setF_state(rs.getString());
user.setF_email(rs.getString());
user.setF_mobilephone(rs.getString());
user.setF_secretaryid(rs.getLong());
user.setF_password(rs.getString());
user.setF_order(rs.getLong());
user.setF_note(rs.getString());
user.setF_infomodifytemplateid(rs.getLong());
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
} public void save(User user) { } public static void main(String[] args) {
UserDaoImpl daoimpl = new UserDaoImpl();
daoimpl.login("admin");
} }
工具类 CookieUtils类
package com.struts.util; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext; import com.struts.action.LoginAction;
import com.struts.proj.User;
import com.struts.service.UserService;
import com.struts.service.impl.UserServiceImpl; public class CookieUtils {
public static final String USER_COOKIE = "user.cookie"; // 增加cookie
public Cookie addCookie(User user) {
Cookie cookie = new Cookie(USER_COOKIE, user.getF_loginname() + ","
+ DESEDE.decryptIt(user.getF_password()));
cookie.setMaxAge( * * * );
return cookie;
} // 得到cookie
public boolean getCookie(HttpServletRequest request, UserService userService) {
request = ServletActionContext.getRequest();
Cookie[] cookies = request.getCookies();
userService = new UserServiceImpl();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (CookieUtils.USER_COOKIE.equals(cookie.getName())) {
String value = cookie.getValue();
// 判断字符是否为空
if (StringUtils.isNotBlank(value)) {
String[] spilt = value.split(",");
String loginname = spilt[];
String password = spilt[];
User user = userService.login(loginname, 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) {
request = ServletActionContext.getRequest();
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (USER_COOKIE.equals(cookie.getName())) {
cookie.setValue("");
cookie.setMaxAge();
return cookie;
}
}
}
return null;
}
}
service层代码,验证用户名和密码是否正确,密码我本地用了加密算法,需要解密,友友们可以去掉
package com.struts.service.impl; import com.struts.dao.UserDao;
import com.struts.dao.impl.UserDaoImpl;
import com.struts.proj.User;
import com.struts.service.UserService;
import com.struts.util.DESEDE; public class UserServiceImpl implements UserService {
UserDao userDao = new UserDaoImpl(); public User login(String loginname, String password) {
User user = userDao.login(loginname);
if (user == null) {
System.out.println("用户名不存在,请检查后重新登录!"); }
if (!DESEDE.decryptIt(user.getF_password()).equals(password)) {
System.out.println("密码错误");
}
return user;
} public static void main(String[] args) {
UserServiceImpl useimp = new UserServiceImpl();
System.out.println(useimp.login("admin", ""));
} }
struts2的配置文件struts.xml,loginAction和ValidateCodeAction验证码的验证
<?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.reload" value="true" />
<constant name="struts.devMode" value="true" />
<package name="loginResult" extends="struts-default" namespace="/">
<action name="loginAction" class="com.struts.action.LoginAction">
<result name="success" type="redirect">/success.jsp</result>
<result name="error">/error.jsp</result>
<result name="login" type="redirect">/login.jsp</result>
</action>
<!-- 验证码 -->
<action name="validate" class="com.struts.action.ValidateCodeAction">
<param name="width"></param>
<param name="height"></param>
<param name="fontSize"></param>
<param name="codeLength"></param>
<result type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
</struts>
web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
action文件类 LoginAction
package com.struts.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.ServletActionContext; import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.struts.proj.User;
import com.struts.service.UserService;
import com.struts.service.impl.UserServiceImpl;
import com.struts.util.CookieUtils;
import com.struts.util.DESEDE; public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 6650955874307814247L;
private String f_loginname;
private String f_password; private HttpServletResponse response;
private HttpServletRequest request;
private Map<String, Object> session;
private CookieUtils cookieUtils = new CookieUtils();
private boolean userCookie; private String validateCode; public static final String USER_SESSION = "user.session"; UserService userService = new UserServiceImpl(); public String autoLogin() throws Exception {
request = ServletActionContext.getRequest();
if (cookieUtils.getCookie(request, userService)) {
return "success";
} else
return "login";
} @Override
public String execute() throws Exception {
HttpSession session = ServletActionContext.getRequest().getSession();
try {
String code = (String) session.getAttribute("validateCode");
if (validateCode == null || !validateCode.equals(code)) {
System.out.println("验证码输入有误,请正确输入");
return "error";
}
if (f_loginname != null && !"".equals(f_loginname)
&& !"".equals(f_password) && f_password != null) {
User user = userService.login(f_loginname, f_password);
// 判断是否要添加到cookie中
String psswd = DESEDE.decryptIt(user.getF_password());
if (user != null && psswd.equals(f_password)) {
if (userCookie) {
Cookie cookie = cookieUtils.addCookie(user);
ActionContext.getContext().get("response");
ServletActionContext.getResponse().addCookie(cookie);
}
session.setAttribute(USER_SESSION, user);
return "success";
}
} } catch (Exception e) {
e.printStackTrace();
}
return "login";
} // 用户退出
public String logout() {
request = ServletActionContext.getRequest();
response = ServletActionContext.getResponse();
HttpSession session = ServletActionContext.getRequest().getSession();
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 static void main(String[] args) {
LoginAction login = new LoginAction();
try {
login.execute();
} catch (Exception e) {
e.printStackTrace();
}
} public Map<String, Object> getSession() {
return session;
} public void setSession(Map<String, Object> session) {
this.session = session;
} public HttpServletResponse getResponse() {
return response;
} public void setResponse(HttpServletResponse response) {
this.response = response;
} public HttpServletRequest getRequest() {
return request;
} public void setRequest(HttpServletRequest request) {
this.request = request;
} public boolean isUserCookie() {
return userCookie;
} public void setUserCookie(boolean userCookie) {
this.userCookie = userCookie;
} public String getF_loginname() {
return f_loginname;
} public void setF_loginname(String fLoginname) {
f_loginname = fLoginname;
} public String getF_password() {
return f_password;
} public void setF_password(String fPassword) {
f_password = fPassword;
} public String getValidateCode() {
return validateCode;
} public void setValidateCode(String validateCode) {
this.validateCode = validateCode;
}
}
验证码 ValidataCodeAction ,网上很多验证码的例子,可以选择自己的方式来写验证码
package com.struts.action; import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random; import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream; import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; public class ValidateCodeAction extends ActionSupport { private static final long serialVersionUID = 1L;
private ByteArrayInputStream inputStream;
private int width;
private int height;
private int fontSize;
private int codeLength; public ValidateCodeAction() {
} public void setCodeLength(int codeLength) {
this.codeLength = codeLength;
} public void setFontSize(int fontSize) {
this.fontSize = fontSize;
} public void setHeight(int height) {
this.height = height;
} public void setWidth(int width) {
this.width = width;
} public ByteArrayInputStream getInputStream() {
return inputStream;
} public void setInputStream(ByteArrayInputStream inputStream) {
this.inputStream = inputStream;
} public String execute() throws Exception {
BufferedImage bimage = new BufferedImage(width, height, );
Graphics g = bimage.getGraphics();
Random random = new Random();
g.setColor(getRandomColor(random, , ));
g.fillRect(, , width, height);
g.setFont(new Font("Times New Roman", , fontSize));
g.setColor(getRandomColor(random, , ));
for (int i = ; i < ; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt();
int yl = random.nextInt();
g.drawLine(x, y, x + xl, y + yl);
} StringBuffer str = new StringBuffer();
for (int i = ; i < codeLength; i++) {
String randomStr = String.valueOf(random.nextInt());
str.append(randomStr);
g.setColor(new Color( + random.nextInt(), + random
.nextInt(), + random.nextInt()));
int x = (width / codeLength - ) * i
+ random.nextInt(width / (codeLength * ));
int y = random.nextInt(height - fontSize) + fontSize;
g.drawString(randomStr, x, y);
} ActionContext.getContext().getSession().put("validateCode",
str.toString());
g.dispose();
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageOutputStream iout = ImageIO.createImageOutputStream(output);
ImageIO.write(bimage, "JPEG", iout);
iout.close();
output.close();
ByteArrayInputStream in = new ByteArrayInputStream(output.toByteArray());
setInputStream(in);
return "success";
} private Color getRandomColor(Random random, int fc, int bc) {
if (fc > )
fc = ;
if (bc > )
bc = ;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
} }
index.jsp页面,如果cookie登录直接进入登录成功页面,没有则跳转到login.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
response.sendRedirect(basePath+"loginAction!autoLogin.action");
%>
login.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ 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>
<title>登录界面</title>
<base href="<%=basePath%>">
<script type="text/javascript" src="<%=path%>/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
function check() {
if ($('#f_loginname').val() == "") {
alert("用户名不能为空!");
$('#f_loginname').focus();
return false;
}
if ($('#f_password').val() == "") {
alert("密码不能为空!");
$('#f_password').focus();
return false;
}
if($('#validateCode').val()==""){
alert("验证码不能为空!");
$('#validateCode').focus();
return false;
}
}
</script>
</head>
<body>
<form name="loginForm" id="loginForm" action="loginAction.action" method="post">
用户名:
<input name="f_loginname" id="f_loginname">
<br>
密 码:
<input type="password" name="f_password" id="f_password">
<font color="red">自动登录</font>
<input id="userCookie" type="checkbox" name="userCookie" value="true" />
<br/>
验证码:
<input name="validateCode" type="text" id="validateCode">
<img src="<%=path %>/validate" width="" height="">
<a href="javascript:location.reload();">看不清?</a>
<!-- false表示不自动登录,为默认值 true表示自动登录,表示选中-->
<br>
<input type="submit" value="提 交" id="login" onclick="return check()">
<input type="reset" value="取 消">
</form>
</body>
</html>
登录成功页面success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.struts.util.CookieUtils"%>
<%@page import="org.apache.commons.lang.xwork.StringUtils"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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>success page</title>
</head> <body>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (CookieUtils.USER_COOKIE.equals(cookie.getName())) {
String value = cookie.getValue();
// 判断字符是否为空
if (StringUtils.isNotBlank(value)) {
String[] spilt = value.split(",");
String loginname = spilt[];
String password = spilt[];
out.println(loginname + "欢迎登陆");
}
}
}
}
%>
<s:a action="loginAction!logout.action" namespace="/"> 安全退出</s:a>
</body>
</html>
struts2与cookie实现自动登录和验证码验证的更多相关文章
- cookie实现自动登录
有很多Web程序中第一次登录后,在一定时间内(如2个小时)再次访问同一个Web程序时就无需再次登录,而是直接进入程序的主界面(仅限于本机).实现这个功能关键就是服务端要识别客户的身份.而用Cookie ...
- C#检测并安装https站点的数字证书,CefSharp和HttpWebRequest通过会话Cookie实现自动登录访问https站点
HttpUtil工具类: using System; using System.Collections.Generic; using System.IO; using System.Linq; usi ...
- 使用cookie实现自动登录
一.从登录——>主页面,进行的过程是,输入 用户名和密码,以及验证码,点击“登录”跳转到Activity.jsp login1.action(跳转到登录页面) /** 跳转到login(有积分排 ...
- 使用cookie下次自动登录
登录时勾选了自动登录处理: 1.加密账号和IP,保存在cookie中,cookie('auto', $value, $time) 2.解密cookie,取出账号和上次IP,判断上次IP==当前IP.账 ...
- cookie技术自动登录
user public class User implements Serializable{ private String username; private String nick; privat ...
- Spring mvc session cookie实现自动登录
设计过程 1. user表存储用户名密码等信息,login表存放用户登陆状态的表 user表中存储username,pwd,等信息 login表存username,series(UUID),token ...
- 如何设计相对安全的cookie自动登录系统
很多网站登录的时候,都会有一个"记住我"功能,用户可以在限定时间段内免登录, 比如豆瓣.人人.新浪微博等都有这种设计.这种技术其实就是基于 cookie的自动登录, 用户登录的时候 ...
- 自己Cookie写的自动登录功能 包含BASE64 和MD5的使用
sql表 username password字段 User类 有 id username password等字段 Service有一函数 @Override public User findUser ...
- 爬虫模拟cookie自动登录(人人网自动登录)
什么是cookie? 在网站中,HTTP请求时无状态的,也就是说即使第一次和服务器连接后并且登录成功后,第二次请求服务器依然不能知道当前请求是谁,cookie的出现就是为了解决这个问题,第一次登陆后服 ...
随机推荐
- 第二百零八天 how can I 坚持
今天徐斌生日,生日快乐.买了两个小蛋糕,哈哈 还买了两条熊猫鱼.不知道鱼会不会冻死啊,买了加热器又不想用,看他们造化吧. LOL不错的游戏的. 睡觉,好冷.
- 转】Spark DataFrames入门指南:创建和操作DataFrame
原博文出自于: http://blog.csdn.net/lw_ghy/article/details/51480358 感谢! 一.从csv文件创建DataFrame 本文将介绍如何从csv文件创建 ...
- HTML5边玩边学(1)画布实现方法
一.<canvas>标签 Html5 引入了一个新的 <canvas> 标签,这个标签所代表的区域就好象一块画布,你的所有图形绘制最后都要在这块画布上呈现.有了这个标签,浏览器 ...
- UVALive 5880 Vigenère Cipher Encryption (模拟)
Stack Machine Executor 题目链接: http://acm.hust.edu.cn/vjudge/problem/26628 Description http://7xjob4.c ...
- Working with Other Node Types II
[Working with Other Node Types II] An SKCropNode object does not directly render content, like a spr ...
- MSDN上面测试Window的方法(很好用)
如何:将 Windows 服务作为控制台应用程序运行 向你运行 OnStart 和 OnStop 方法的服务添加一个方法: internal void TestStartupAndStop(s ...
- Oracle日志文件管理与查看
Oracle日志文件管理与查看 from:http://hi.baidu.com/shuker/item/25ee611ee960c7426826bb1f 1.查询系统使用的是哪一组日志文件: sel ...
- HDU 5164Matching on Array(AC自动机)
这是BC上的一道题,当时比赛没有做,回头看看题解,说是AC自动机,想着没有写过AC自动机,于是便试着抄抄白书的模板,硬是搞了我数个小时2000ms时限1800过了= = ! 这里就直接贴上BC的结题报 ...
- POJ1201Intervals(差分约束系统)
昨天看了下差分约数系统的含义,其实就是如果有n个变量在m个形如aj-ai>=bk条件下,求解的此不等式的方法. 而这种不等式的解法其实就是转化为图论的最小路的算法求解的.我们将上面的不等式边形后 ...
- UVa 10316 - Airline Hub
题目:给出地球上的n个机场的经度和纬度,想在这里面确定一个HUB使得他到其他机场的最大距离最小. 分析:计算几何.大地坐标系.因为数据不大直接枚举即可,比较时利用圆心角可以提高计算效率,并控制精度. ...