jsp页面生成

时间:2021-05-12 17:07:49

1 生成验证码图片类

  1 package com.keertech.util;
2
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics;
6 import java.awt.image.BufferedImage;
7 import java.io.ByteArrayInputStream;
8 import java.io.ByteArrayOutputStream;
9 import java.io.IOException;
10 import java.util.Random;
11 import javax.imageio.ImageIO;
12 import javax.imageio.stream.ImageOutputStream;
13 import javax.servlet.ServletException;
14 import javax.servlet.http.HttpServlet;
15 import javax.servlet.http.HttpServletRequest;
16 import javax.servlet.http.HttpServletResponse;
17
18 /**
19 * generate validate image
20 * @author kunbao li
21 * @date 2010-03-08
22 */
23 public class VImage extends HttpServlet {
24 /**
25 * serialVersionUID
26 */
27 private static final long serialVersionUID = 1L;
28
29 private ByteArrayInputStream image;
30
31 public ByteArrayInputStream getImage() {
32 return image;
33 }
34
35 public void setImage(ByteArrayInputStream image) {
36 this.image = image;
37 }
38
39 Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
40 Random random = new Random();
41 if (fc > 255)
42 fc = 255;
43 if (bc > 255)
44 bc = 255;
45 int r = fc + random.nextInt(bc - fc);
46 int g = fc + random.nextInt(bc - fc);
47 int b = fc + random.nextInt(bc - fc);
48 return new Color(r, g, b);
49 }
50
51 public void doGet(HttpServletRequest request, HttpServletResponse response)
52 throws ServletException, IOException {
53
54 // 设置页面不缓存
55
56 response.setHeader("Pragma", "No-cache");
57 response.setHeader("Cache-Control", "no-cache");
58 response.setDateHeader("Expires", 0);
59
60 // 在内存中创建图象
61 int width = 60, height = 20;
62 BufferedImage image = new BufferedImage(width, height,
63 BufferedImage.TYPE_INT_RGB);
64
65 // 获取图形上下文
66
67 Graphics g = image.getGraphics();
68
69 // 生成随机类
70
71 Random random = new Random();
72
73 // 设定背景色
74
75 g.setColor(getRandColor(200, 250));
76 g.fillRect(0, 0, width, height);
77
78 // 设定字体
79 g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
80
81 // 画边框
82
83 // g.setColor(new Color());
84 // g.drawRect(0,0,width-1,height-1);
85
86 // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
87
88 g.setColor(getRandColor(160, 200));
89 for (int i = 0; i < 155; i++) {
90 int x = random.nextInt(width);
91 int y = random.nextInt(height);
92 int xl = random.nextInt(12);
93 int yl = random.nextInt(12);
94 g.drawLine(x, y, x + xl, y + yl);
95 }
96
97 // 取随机产生的认证码(4位数字)
98 String sRand = "";
99 for (int i = 0; i < 4; i++) {
100 String rand = String.valueOf(random.nextInt(10));
101 sRand += rand;
102 // 将认证码显示到图象中
103 g.setColor(new Color(20 + random.nextInt(110), 20 + random
104 .nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
105
106 g.drawString(rand, 13 * i + 6, 16);
107 }
108
109 //将认证码存入SESSION
110 request.getSession().setAttribute("rand", sRand);
111
112 // 图象生效
113 g.dispose();
114
115 ByteArrayInputStream input = null;
116 ByteArrayOutputStream output = new ByteArrayOutputStream();
117 try {
118 ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
119 // 输出图象到页面
120
121 ImageIO.write(image, "JPEG", imageOut);
122 imageOut.close();
123 input = new ByteArrayInputStream(output.toByteArray());
124 } catch (Exception e) {
125 //not handle
126 }
127
128 this.image = input;
129 }
130 }

2 验证码图片action

 1 package com.keertech.web.action;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import javax.servlet.ServletException;
6 import org.apache.log4j.Logger;
7 import org.apache.struts2.ServletActionContext;
8
9 import com.keertech.base.action.AbstractAction;
10 import com.keertech.util.VImage;
11
12
13 public class ImageAction extends AbstractAction {
14 /**
15 * serialVersionUID
16 */
17 private static final long serialVersionUID = 1L;
18
19 /**
20 * log
21 */
22 private Logger log = Logger.getLogger(this.getClass().getName());
23
24 private ByteArrayInputStream inputStream;
25
26 public String getValCode(){
27 VImage v=new VImage();
28 try {
29 v.doGet(ServletActionContext.getRequest(), ServletActionContext.getResponse());
30 this.setInputStream(v.getImage());
31 } catch (ServletException e) {
32 log.info(e.getMessage());
33 } catch (IOException e) {
34 log.info(e.getMessage());
35 }
36
37 return SUCCESS;
38 }
39
40 public ByteArrayInputStream getInputStream() {
41 return inputStream;
42 }
43
44 public void setInputStream(ByteArrayInputStream inputStream) {
45 this.inputStream = inputStream;
46 }
47 }

3 struts配置aciton

1 <action name="rand" class="com.keertech.web.action.ImageAction"
2 method="getValCode">
3 <result type="stream">
4 <param name="contentType">image/jpeg</param>
5 <param name="inputName">inputStream</param>
6 </result>
7 </action>

4 javascript访问验证码生成action

1 function changeValidateCode(obj) {
2 var myDate = new Date();
3 obj.src = "webbase/rand.action?date=" + myDate;
4 }

5 html

1 <img style="display: block;float: left;cursor:hand;" src="rand.action" id="valImg" onclick="changeValidateCode(this)" title="更换验证码" />

6 接收数据action中核对验证码是否正确

 1 Boolean valided = true;
2
3 if (valided){
4 if (valCode == null || valCode.equals("") || valCode.trim().equals("")) {
5 response(String.format("{\"success\":false,\"message\":\"%s\"}","验证码不能为空"));
6 valided = Boolean.FALSE;
7 }
8 else {
9 String tmp = (String) request.getSession().getAttribute("rand");
10 if (!valCode.equalsIgnoreCase(tmp)) {
11 response(String.format("{\"success\":false,\"message\":\"%s\"}","验证码错误"));
12 valided = Boolean.FALSE;
13 }
14 }
15 }

7 javascript提交

 1 var param = 'name=' + name +                    
2 '&regMail=' + regMail +
3 '&contacter=' + contacter +
4 '&cellPhone=' + cellPhone +
5 '&valCode=' + valCode;
6 $.post('enterpriseManage!registerEnterprise.action', param, function(result) {
7 if (result.success) {
8 //$('#pu_msg').html("您好,欢迎注册八鸽快消通软件。请登录到您的注册邮箱激活您的账号。");
9 } else {
10 /*
11 $('#pu_msg').html(result.message);
12 $('#pu_loginName').select();
13 */
14 alert("验证码有误,请重新填写");
15 var valImg = document.getElementById("valImg");
16 changeValidateCode(valImg);
17 }
18 }, "json");