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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 验证码图形生成
* @version 1.0
* */
public class AuthImg extends HttpServlet
{
//设置图形验证码的字符串文字类型
private Font mfont=new Font("Arial",Font.PLAIN,16);
public void init() throws ServletException
{
super.init();
}
//验证码的颜色
private Color getRandColor(int fc,int bc)
{
Random random=new Random();
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);
}
//服务器生成字符串方法
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException
{
//清除页面上的缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0); //过期时间
response.setContentType("image/jpeg");
//设置验证码图形的大小
int width=100,height=18;
BufferedImage img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g=img.getGraphics();
Random random=new Random();
g.setColor(getRandColor(200,255));
g.fillRect(1, 1, width-1, height-1); //设置矩形的起始位置
g.setColor(new Color(103,105,106));
g.drawRect(0, 0, width-1, height-1);
g.setFont(mfont);
//随机生成线条
for(int i=0;i<155;i++)
{
int x=random.nextInt(width-1);
int y=random.nextInt(height-1);
int x2=random.nextInt(5)+1;
int y2=random.nextInt(8)+1;
g.drawLine(x, y, x+x2, y+y2);
}
//随机生成线条
for(int i=0;i<55;i++)
{
int x=random.nextInt(width-1);
int y=random.nextInt(height-1);
int x2=random.nextInt(5)+1;
int y2=random.nextInt(8)+1;
g.drawLine(x, y, x-x2, y-y2);
}
//随机数存储
String sRand="";
for(int i=0;i<5;i++)
{
//取得随机数
String tmp=getRandomChar();
sRand+=tmp;
g.setColor(new Color(20+random.nextInt(120),20+random.nextInt(120),20+random.nextInt(120)));
g.drawString(tmp, 10*i+10, 15);
}
//取得用户session
HttpSession s=request.getSession(true);
s.setAttribute("sRand", sRand);
g.dispose();
ImageIO.write(img, "JPEG", response.getOutputStream());
}
//生成随机字符串
private String getRandomChar()
{
int rand=(int)Math.round(Math.random()*2);
long itmp=0;
char ctmp='\u0000';
//根据随机数判断是生成大小写字母和数字
switch(rand)
{
case 1:
//大写字母
itmp=Math.round(Math.random()*25+65);
ctmp=(char)itmp;
return String.valueOf(ctmp);
case 2:
//小写字母
itmp=Math.round(Math.random()*25+97);
ctmp=(char)itmp;
return String.valueOf(ctmp);
default:
//生成数字
itmp=Math.round(Math.random()*9);
return String.valueOf(itmp);
}
}
}
servlet生成验证码--非常的简单
最新推荐文章于 2025-05-23 17:03:50 发布