struts2验证码登陆实现
Posted Richard_i
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts2验证码登陆实现相关的知识,希望对你有一定的参考价值。
首先是生成图片的Action:
package actions;
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.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class CreateImageAction extends ActionSupport
private ByteArrayInputStream inputStream;
private static int WIDTH = 60;
private static int HEIGHT = 20;
public ByteArrayInputStream getInputStream()
return inputStream;
public void setInputStream(ByteArrayInputStream inputStream)
this.inputStream = inputStream;
private static String createRandom()
String str = "0123456789qwertyuiopasdfghjklzxcvbnm";
char[] rands = new char[4];
Random random = new Random();
for (int i = 0; i < 4; i++)
rands[i] = str.charAt(random.nextInt(36));
return new String(rands);
private void drawBackground(Graphics g)
// 画背景
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, WIDTH, HEIGHT);
// 随机产生 120 个干扰点
for (int i = 0; i < 120; i++)
int x = (int) (Math.random() * WIDTH);
int y = (int) (Math.random() * HEIGHT);
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(new Color(red, green, blue));
g.drawOval(x, y, 1, 0);
private void drawRands(Graphics g, String rands)
g.setColor(Color.BLACK);
g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));
// 在不同的高度上输出验证码的每个字符
g.drawString("" + rands.charAt(0), 1, 17);
g.drawString("" + rands.charAt(1), 16, 15);
g.drawString("" + rands.charAt(2), 31, 18);
g.drawString("" + rands.charAt(3), 46, 16);
System.out.println(rands);
public String execute() throws Exception
HttpServletResponse response = ServletActionContext.getResponse();
// 设置浏览器不要缓存此图片
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
String rands = createRandom();
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 产生图像
drawBackground(g);
drawRands(g, rands);
// 结束图像 的绘制 过程, 完成图像
g.dispose();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", outputStream);
ByteArrayInputStream input = new ByteArrayInputStream(outputStream
.toByteArray());
this.setInputStream(input);
HttpSession session = ServletActionContext.getRequest().getSession();
session.setAttribute("checkCode", rands);
input.close();
outputStream.close();
return SUCCESS;
以上是生成随机验证码图片的action,将生成的随机数放到session里,然后页面提交到验证随机数的action:
package actions;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import beans.User;
import beans.UserDao;
public class Login_Action extends ActionSupport
private User user;
private String checkCode;
public User getUser()
return user;
public void setUser(User user)
this.user = user;
public String getCheckCode()
return checkCode;
public void setCheckCode(String checkCode)
this.checkCode = checkCode;
public String execute() throws Exception
return SUCCESS;
@Override
public void validate()
HttpSession session = ServletActionContext.getRequest().getSession();
String checkCode2 = (String)session.getAttribute("checkCode");
if(!checkCode.equals(checkCode2))
addFieldError(checkCode, "输入的验证码不正确,请重新输入");
下面是struts.xml配置部分代码:
<action name="login" class="actions.Login_Action">
<result name="success">/login_Success.jsp</result>
<result name="input">/login.jsp</result>
</action>
<action name="createImageAction" class="actions.CreateImageAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>
</action>
最后就是jsp部分的代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function refresh()
//IE存在缓存,需要new Date()实现更换路径的作用
document.getElementById("image").src="createImageAction.action?+ Math.random()"+new Date();
</script>
<title>登陆页面</title>
</head>
<body>
<center>
<h3>用户登录</h3>
<s:fielderror cssStyle="color:red"></s:fielderror>
<s:form action="login.action" method="post" name="code">
<s:textfield name="user.userName" label="用户名"/>
<s:textfield name="user.userPwd" label="用户密码"/><br>
<s:textfield name="checkCode" maxlength="4" label="验证码"/>
验证码:<img id="image" border="0" οnclick="refresh()" src="createImageAction.action" title="看不清,换一张">
<s:submit value="登陆"/>
<s:reset value="重新输入"/>
<s:url ></s:url>
<a href="register.jsp">尚未注册,点击注册</a>
</s:form>
</center>
</body>
</html>
到此,就完成用struts2生成随机验证码图片以及实现登陆验证啦!
以上是关于struts2验证码登陆实现的主要内容,如果未能解决你的问题,请参考以下文章