servlet
package cn.itcast.web.response;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
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;
public class RandomValidateCodeServlet extends HttpServlet {
public static final int WIDTH = 120;
public static final int HEIGHT = 30;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
// 1.设置背景色
setBackGround(g);
// 2.设置边框
setBorder(g);
// 3.画干扰线
drawRandomLine(g);
// 4.写随机数
drawRandomNum(g);
// 5.图形写给浏览器
response.setContentType("image/jpeg");
// 发头控制浏览器不要缓存
response.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
ImageIO.write(image, "jpg", response.getOutputStream());
}
private void drawRandomNum(Graphics g) {
g.setColor(Color.RED);
g.setFont(new Font("宋体", Font.BOLD, 20));
// [\u4e00-\u9fa5] 汉字区间
String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762";
int x = 5;
for (int i = 0; i < 4; i++) {
String ch = "" + base.charAt(new Random().nextInt(base.length()));
g.drawString(ch, x, 20);
x += 30;
}
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.GREEN);
for (int i = 0; i < 4; i++) {
int x1 = new Random().nextInt(WIDTH);
int y1 = new Random().nextInt(HEIGHT);
int x2 = new Random().nextInt(WIDTH);
int y2 = new Random().nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
}
private void setBorder(Graphics g) {
g.setColor(Color.BLUE);
g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
}
private void setBackGround(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}