struts2 验证码实例
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
运行效果:
我参考别人代码写的一个简单的例子:
Java代码
1package org.apache.struts.action;
2
3import java.awt.Color;
4import java.awt.Font;
5import java.awt.Graphics;
6import java.awt.image.BufferedImage;
7import java.io.ByteArrayInputStream;
8import java.io.ByteArrayOutputStream;
9import java.util.Random;
10
11import javax.imageio.ImageIO;
12import javax.imageio.stream.ImageOutputStream;
13
14import com.opensymphony.xwork2.ActionContext;
15import com.opensymphony.xwork2.ActionSupport;
16
17public class RandomPictureAction extends ActionSupport {
18
19/**
20*
21*/
22private static final long serialVersionUID = -6950908478971552308L; 23
24private ByteArrayInputStream inputStream;
25
26public String execute()throws Exception {
27// 在内存中创建图象
28int width =85, height =20;
29
30BufferedImage image =new BufferedImage(width, height,
31BufferedImage.TYPE_INT_RGB);
32
33// 获取图形上下文
34Graphics g = image.getGraphics();
35
36// 生成随机类
37Random random =new Random();
38
39// 设定背景色
40g.setColor(getRandColor(200,250));
41g.fillRect(0,0, width, height);
42
43// 设定字体
44g.setFont(new Font("Times New Roman", Font.PLAIN,18));
45
46// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到47g.setColor(getRandColor(160,200));
48for(int i =0; i <155; i++) {
49int x = random.nextInt(width);
50int y = random.nextInt(height);
51int xl = random.nextInt(12);
52int yl = random.nextInt(12);
53g.drawLine(x, y, x + xl, y + yl);
54}
55
56// 取随机产生的认证码(6位数字)
57String sRand ="";
58for(int i =0; i <6; i++) {
59String rand = String.valueOf(random.nextInt(10));
60sRand += rand;
61// 将认证码显示到图象中
62g.setColor(new Color(20+ random.nextInt(110),20+ random
63.nextInt(110),20+ random.nextInt(110)));
64// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成65g.drawString(rand,13* i +6,16);
66}
67
68// 将认证码存入SESSION
69ActionContext.getContext().getSession().put("rand", sRand);
70
71// 图象生效
72g.dispose();
73ByteArrayOutputStream output =new ByteArrayOutputStream();
74ImageOutputStream imageOut =
ImageIO.createImageOutputStream(output);
75ImageIO.write(image,"JPEG", imageOut);
76imageOut.close();
77ByteArrayInputStream input =new ByteArrayInputStream(output 78.toByteArray());
79this.setInputStream(input);
80return SUCCESS;
81}
82