package arithmetic_web;
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;
/**
* 通过servlet生成验证码
* @author liujd
*
*/
public class AuthCode extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//告诉浏览器当做图片处理
resp.setContentType("image/jpeg");
//告诉浏览器不缓存
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");
resp.setHeader("expires", "0");
//产生由四位数字,字母构成的验证码
int length = 4;
String[] code = {"0","1","2","3","4","5","6","7","8","9",
"a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s","t",
"u","v","w","x","y","z","A","B","C","D","E","F"
,"F","H","I","J","K","L","M","N","O","P","Q","R","S"
,"T","U","V","W","X","Y","Z"};
StringBuilder authCode = new StringBuilder("");
Random random = new Random();
for(int i = 0 ; i<length ; i++)
authCode.append(code[random.nextInt(code.length)]);
//把产生的验证码放到session里面
HttpSession session = req.getSession();
session.setAttribute("authCode", authCode);
//产生图片
int width = 70;
int height = 20;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取一个Graphics(java中一个绘图类)
Graphics g = img.getGraphics();
//设置背景色
g.setColor(Color.WHITE);
//填充指定的矩形
g.fillRect(0, 0, width, height);
//填充干扰线
for(int i = 0 ; i<100 ; i++) {
g.setColor(new Color(random.nextInt(100)+155,random.nextInt(100)+155,random.nextInt(100)+155));
//使用当前颜色在(x1,y1)和(x2,y2)之间画线
g.drawLine(random.nextInt(width), random.nextInt(height),random.nextInt(width), random.nextInt(height));
}
// 绘制边框
g.setColor(Color.GRAY);
g.drawRect(0, 0, width-1, height-1);
// 绘制验证码(随机的字体)
Font[] fonts = {new Font("隶书",Font.BOLD,18),new Font("楷体",Font.BOLD,18),new Font("宋体",Font.BOLD,18),new Font("幼圆",Font.BOLD,18)};
for(int i=0; i<length; i++){
//利用当前颜色,字体绘制验证码
g.setColor(new Color(random.nextInt(150),random.nextInt(150),random.nextInt(150)));
g.setFont(fonts[random.nextInt(fonts.length)]);
//验证码出现位置
g.drawString(authCode.charAt(i)+"", width/authCode.length()*i+2, 18);
}
// 释放此图形的上下文以及它使用的所有系统资源。
g.dispose();
ImageIO.write(img, "jpeg", resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
利用servlet绘制验证码
最新推荐文章于 2023-06-08 21:04:44 发布