struts2生成随机验证码图片
之前想做一个随机验证码的功能,自己也搜索了一下别人写的代码,然后自己重新用struts2实现了一下,现在将我自己实现代码贴出来!大家有什么意见都可以指出来!
首先是生成随机验证码图片的action:
CreateImageAction:

package com.xiaoluo.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.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); } @Override
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:
LoginValidateAction:

package com.xiaoluo.action; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class LoginValidateAction extends ActionSupport
{
private String checkCode; public String getCheckCode()
{
return checkCode;
} public void setCheckCode(String checkCode)
{
this.checkCode = checkCode;
} @Override
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))
{
this.addActionError("输入的验证码不正确,请重新输入!");
}
}
}

下面是struts.xml配置部分代码:

<action name="createImageAction" class="com.xiaoluo.action.CreateImageAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>
</action> <action name="loginValidateAction" class="com.xiaoluo.action.LoginValidateAction">
<result name="success">/success.jsp</result>
<result name="input">/login.jsp</result>
</action>

最后就是jsp部分的代码:
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+"/";
%> <html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body> <h3><font color="blue">带有验证码的登陆界面</font></h3> <s:form action="loginValidateAction.action" theme="simple"> 用户名:<s:textfield name="username"></s:textfield><br>
密码 :<s:password name="password"></s:password><br>
验证码:<s:textfield name="checkCode"></s:textfield>
<!--若要点击图片刷新,重新得到一个验证码,要在后面加上个随机数,这样保证每次提交过去的都是不一样的path,防止因为缓存而使图片不刷新-->
<img src="createImageAction.action" onclick="this.src='createImageAction.action?'+ Math.random()" title="点击图片刷新验证码"/><br>
<s:actionerror cssStyle="color:red"/> <s:submit value="提交"></s:submit> </s:form> </body>
</html>

到此,就完成用struts2生成随机验证码图片以及实现登陆验证啦!
struts2生成随机验证码图片的更多相关文章
- .net生成随机验证码图片
/// <summary> /// 自定义图片验证码函数 /// 该函数将生成一个图片验证码,并将生成的code存放于Session["VerifyCode"]变量内. ...
- Python利用PIL生成随机验证码图片
安装pillow: pip install pillow PIL中的Image等模块提供了创建图片,制作图片的功能,大致的步骤就是我们利用random生成6个随机字符串,然后利用PIL将字符串绘制城图 ...
- python模块之PIL模块(生成随机验证码图片)
PIL简介 什么是PIL PIL:是Python Image Library的缩写,图像处理的模块.主要的类包括Image,ImageFont,ImageDraw,ImageFilter PIL的导入 ...
- java生成随机验证码图片
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; i ...
- Python使用PIL模块生成随机验证码
PIL模块的安装 pip3 install pillow 生成随机验证码图片 import random from PIL import Image, ImageDraw, ImageFont fro ...
- Java生成随机验证码
package com.tg.snail.core.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphic ...
- Python 生成随机验证码
Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 fro ...
- Python生成随机验证码
Python生成随机验证码,需要使用PIL模块. 安装: pip3 install pillow 基本使用 1.创建图片 from PIL import Image img = Image.new(m ...
- java生成简单验证码图片
概要 最近项目需要用java实现输出随机验证码图片到前台,正好有机会接触下java的绘图类,完成需求后也有时间做个总结,写篇随笔记录下也希望能帮助到有同样需求的人! 需求流程图 1.生成随机数 在ja ...
随机推荐
- iOS 警告收录及科学快速的消除方法
http://www.cocoachina.com/ios/20150914/13287.html 作者:董铂然 授权本站转载. 前言:现在你维护的项目有多少警告?看着几百条警告觉得心里烦么?你真的觉 ...
- Cmakelists.txt中配置glfw
qt中需要用cmake编译工程,且需要用到OpenGL库glfw,如何给Cmakelist.txt配置glfw的动态链接库? 在Cmakelists.txt添: find_package(glfw3 ...
- ssh scp nc
ssh远程连接 ssh root@192.168.111.11 scp数据传输,(secure copy) 1.下载.拉取 scp root@192.168.111.11:/root/database ...
- iOS Animation 主流炫酷动画框架(特效)收集整理 #91
https://github.com/sxyx2008/DevArticles/issues/91
- 2019-7-20-win10-uwp-使用-msbuild-命令行编译-UWP-程序
title author date CreateTime categories win10 uwp 使用 msbuild 命令行编译 UWP 程序 lindexi 2019-07-20 21:56:2 ...
- 国内唯一,阿里云入选全球区块链云服务报告,领先AWS、Google
摘要: 作为此次Gartner报告中唯一上榜的中国科技公司,阿里云获得六个评判维度的最高分,排名第二 近日,知名调研机构Gartner发布了全球领先公共云厂商区块链服务能力报告,作为唯一上榜的中国科技 ...
- @loj - 2865@ 「IOI2018」狼人
目录 @description@ @solution@ @accepted code@ @details@ @description@ 在日本的茨城县内共有 N 个城市和 M 条道路.这些城市是根据人 ...
- Android GDI 图形渲染
发布于2011-07-26 导读:对于Android开发者来说,成系列的技术文章对他们的技术成长帮助最大.如下是我们向您强烈推荐的主题为Android开发的第一个系列文章. <Andro ...
- IDEA使用中文api鼠标提示的设置
最近都在用IDEA来练习,发现有的方面确实比eclipse好用,eclipse里面可添加中文的API 提示,对初期的我帮助很大,但是IDEA却没有找到添加的地方,一直以来还以为不支持这个功能,比较遗憾 ...
- oracle函数 INSTRB(C1,C2[,I[,J]])
[功能]在一个字符串中搜索指定的字符,返回发现指定的字符的位置; [说明]多字节符(汉字.全角符等),按2个字符计算 [参数] C1 被搜索的字符串 C2 希望搜索的字符串 I 搜 ...