Color=#cccccc cellSpacing=0 cellPadding=1 width="80%" align=center bgColor=#ffffff border=1 heihgt="">
001 package com.rolia.learning.learningweb.validationcode;
002
003 /*
004 * 创建日期 2006-7-23
005 *
006 * TODO 要更改此生成的文件的模板,请转至
007 * 窗口 - 首选项 - Java - 代码样式 - 代码模板
008 * 参数:
009 * count:验证码的字符个数
010 * width:验证码图片宽度
011 * height:验证码图片高度
012 * type:类型 0-纯数字 1-纯大写字母 2-数字和大学字母混合
013 * 功能:生成验证码图片,将验证码保存进session里
014 */
015 import java.io.IOException;
016
017 import javax.Servlet.ServletConfig;
018 import javax.Servlet.ServletException;
019 import javax.Servlet.http.HttpServlet;
020 import javax.Servlet.http.HttpServletRequest;
021 import javax.Servlet.http.HttpServletResponse;
022
023 import java.awt.*;
024 import java.awt.image.*;
025 import java.util.*;
026 import javax.imageio.*;
027 /**
028 * @author Rolia
029 *
030 * TODO 要更改此生成的类型注释的模板,请转至
031 * 窗口 - 首选项 - Java - 代码样式 - 代码模板
032 */
033 public class ValidationCodeServlet extends HttpServlet {
034
035 /**
036 *
037 */
038 private static final long serialVersionUID = 1L;
039 private final int TYPE_NUMBER = 0;
040 private final int TYPE_LETTER = 1;
041 private final int TYPE_MULTIPLE = 2;
042 private int width;
043 private int height;
044 private int count;
045 private int type;
046 private String validate_code;
047 private Random random;
048 private Font font;
049 private int line;
050
051 @Override
052 public void init(ServletConfig config) throws ServletException {
053 super.init(config);
054 width = 150;
055 height = 50;
056 count = 4;
057 type = TYPE_NUMBER;
058 random = new Random();
059 line = 200;
060 }
061
062 @Override
063 protected void doGet(HttpServletRequest request,
064 HttpServletResponse response) throws ServletException, IOException {
065 response.setHeader("Pragma","No-cache");
066 response.setHeader("Cache-Control","no-cache");
067 response.setDateHeader("Expires", 0);
068 response.setContentType("image.jpeg");
069
070 String reqCount = request.getParameter("count");
071 String reqWidth = request.getParameter("width");
072 String reqHeight = request.getParameter("height");
073 String reqType = request.getParameter("type");
074
075 if(reqCount!=null && reqCount!="")this.count = Integer.parseInt(reqCount);
076 if(reqWidth!=null && reqWidth!="")this.width = Integer.parseInt(reqWidth);
077 if(reqHeight!=null && reqHeight!="")this.height = Integer.parseInt(reqHeight);
078 if(reqType!=null && reqType!="")this.type = Integer.parseInt(reqType);
079
080 font = new Font("Courier New",Font.BOLD,width/count);
081
082 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
083
084 Graphics g = image.getGraphics();
085
086 g.setColor(getRandColor(200,250));
087 g.fillRect(0, 0, width, height);
088
089 g.setColor(getRandColor(160,200));
090 for (int i=0;i<line;i++){
091 int x = random.nextInt(width);
092 int y = random.nextInt(height);
093 int xl = random.nextInt(12);
094 int yl = random.nextInt(12);
095 g.drawLine(x,y,x+xl,y+yl);
096 }
097
098 g.setFont(font);
099 validate_code = getValidateCode(count,type);
100 request.getSession().setAttribute("validate_code",validate_code);
101 for (int i=0;i<count;i++){
102 g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
103 int x = (int)(width/count)*i;
104 int y = (int)((height+font.getSize())/2)-5;
105 g.drawString(String.valueOf(validate_code.charAt(i)),x,y);
106 }
107
108 g.dispose();
109 ImageIO.write(image, "JPEG", response.getOutputStream());
110 }
111
112 @Override
113 protected void doPost(HttpServletRequest request,
114 HttpServletResponse response) throws ServletException, IOException {
115 doGet(request, response);
116 }
117
118 private Color getRandColor(int from,int to){
119 Random random = new Random();
120 if(to>255) from=255;
121 if(to>255) to=255;
122 int rang = Math.abs(to - from);
123 int r=from+random.nextInt(rang);
124 int g=from+random.nextInt(rang);
125 int b=from+random.nextInt(rang);
126 return new Color(r,g,b);
127 }
128
129 private String getValidateCode(int size,int type){
130 StringBuffer validate_code = new StringBuffer();
131 for(int i = 0; i < size; i++){
132 validate_code.append(getOneChar(type));
133 }
134 return validate_code.toString();
135 }
136 private String getOneChar(int type){
137 String result = null;
138 switch(type){
139 case TYPE_NUMBER:
140 result = String.valueOf(random.nextInt(10));
141 break;
142
143 case TYPE_LETTER:
144 result = String.valueOf((char)(random.nextInt(26)+65));
145 break;
146
147 case TYPE_MULTIPLE:
148 if(random.nextBoolean()){
149 result = String.valueOf(random.nextInt(10));
150 }else{
151 result = String.valueOf((char)(random.nextInt(26)+65));
152 }
153 break;
154 default:
155 result=null;
156 break;
157 }
158 if(result==null)throw new NullPointerException("获取验证码出错");
159 return result;
160 }
161 }
web.xml
<!-- 生成图片验证码 -->
<Servlet>
<Servlet-name>validationcodeServlet</Servlet-name>
<Servlet-class>com.rolia.learning.learningweb.validationcode.ValidationCodeServlet</Servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-name>validationcodeServlet</Servlet-name>
<url-pattern>/ValidateCodeServlet</url-pattern>
</Servlet-mapping>
validationcode_show.JSP
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title></title>
</head>
<body bgcolor="#FFFFFF">
<form action="validationcode_heck.JSP" method=post>
<table align=center>
<tr><td>
请输入验证码:<input type='text' name='validate_code' size=20>
</td><td>
<img src="ValidateCodeServlet" width=150 height=50>
</td></tr>
<tr><td>
<input type="submit" value="提交">
</td><td>
<input type="reset" value="重填">
</td></tr>
</table>
</form>
</body>
</html>
validationcode_check.JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>Lomboz JSP</title>
</head>
<body bgcolor="#FFFFFF">
<%
String session_validate_code = (session.getAttribute("validate_code")).toString();
if(session_validate_code==null)System.out.println("validate code has not set");
else{
String request_code = request.getParameter("validate_code");
if(request_code==null)out.println("未输入");
else{
if(request_code.equalsIgnoreCase(session_validate_code))out.println("匹配");
else out.println("不匹配");
}
}
%>
</body>
</html>