实现验证码的java代码
转自: http://weirui862868569.blog.163.com/blog/static/13656101620114764749377/
package service;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RandomImg extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = -5981700888850353189L;
@SuppressWarnings("static-access")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("image/jpeg"); //必须设置ContentType为image/jpeg
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",0);
//设置图片的长宽 验证码长度
int width=76, height=20,len=4;
String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int length = base.length();
//创建内存图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取图形上下文
Graphics g = image.getGraphics();
//创建随机类的实例
Random random = new Random();
//设定图像背景色(因为是做背景,所以偏淡)
g.setColor(getRandColor(random,200,250));
g.fillRect(0, 0, width, height);
//备选字体
String[] fontTypes = {"tahoma","Atlantic Inline","fantasy","Times New Roman","Georgia","Arial", "Helvetica", "sans-serif","System"};
int fontTypesLength = fontTypes.length;
//在图片背景上增加噪点
g.setColor(getRandColor(random,160,200));
g.setFont(new Font("Times New Roman",Font.PLAIN,12));
for (int i=0;i<6;i++)
{
g.drawString("!@#$%^,.;'[javawind.net]/<&*()>:5277",0,5*(i+2));
}
String sRand="",pStr="";
for (int i=0;i<len;i++)
{
int start = random.nextInt(length);
String rand=base.substring(start,start+1);
sRand+=rand;
//设置字体的颜色
g.setColor(getRandColor(random,10,150));
//设置字体
g.setFont(new Font(fontTypes[random.nextInt(fontTypesLength)],Font.BOLD,16));
//将随机验证码画到图片上
//g.drawString(rand,15*i,18);
pStr = sRand.substring(i,i+1);
if(i==0){
g.drawString(pStr,2,14);
}
if(i==1){
g.drawString(pStr,15,16);
}
if(i==2){
g.drawString(pStr,30,15);
}
if(i==3){
g.drawString(pStr,45,13);
}
}
//将认证码存入session
sRand = sRand.toLowerCase();
request.getSession().setAttribute("rand",sRand);
g.dispose();
//输出图象到页面
ImageIO.write(image,"JPEG",response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected Color getRandColor(Random random,int fc,int bc)
{
if(fc>255) fc=255;
if(bc>255) bc=255;
int r=fc+random.nextInt(bc-fc);
int g=fc+random.nextInt(bc-fc);
int b=fc+random.nextInt(bc-fc);
return new Color(r,g,b);
}
}
二、web.xml中配置上一个类为servlet:
<servlet>
<servlet-name>showImgCode</servlet-name>
<servlet-class>service.RandomImg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showImgCode</servlet-name>
<url-pattern>/random</url-pattern>
</servlet-mapping>
三、在登录页面中加入验证码,并把struts2标签库改成html标签:
<form action="login.action">
<table>
<tr>
<td width="87" height="30" align="right">用户名:</td>
<td valign="middle"><input type="text" name="userName" tabindex="1" style="width:160px;"></td>
</tr>
<tr>
<td height="30" align="right">密 码:</td>
<td><INPUT name="userPass" type="password" tabindex="2" style="width:160px;"></td>
</tr>
<tr>
<td height="30" align="right">身 份:</td>
<td><select name="identityId">
<option value=1>教务管理</option>
<option value=2>收费管理</option>
<option value=3>工资管理</option>
</select>
</td>
</tr>
<tr>
<td height="30" align="right">验证码:</td>
<td height="30" valign=middle><input type=text name="checkCode" maxLength=6 size="9" tabindex="3">
<IMG style="cursor:hand;border:1px solid #FF6633;" src="random" onClick="this.src=this.src;" > </td>
</tr>
<tr>
<td colspan=2 align=right>
<input type="submit" value="登录" style="width:60px;"/>
</td>
</tr>
</table>
</form>
四、在登录LoginAction中加入:
Map session = ActionContext.getContext().getSession();
String rand = (String)session.get("rand");
if(checkCode.equals(rand))
{
if(p_userDao.login(userName, userPass, identityId))
{
if(identityId == 1)
{
session.put("loginName_teach", userName);
return "teach";
}
else if(identityId == 2)
{
session.put("loginName_finance", userName);
return "finance";
}
else
{
session.put("loginName_salary", userName);
return "salary";
}
}else
{
addActionMessage("您所输入的用户名密码有误");
return "error";
}
}else
{
addActionMessage("您所输入的验证码有误,请重新输入");
return "error";
}