Servlet-Response实现验证码
package com.levizhao.response;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCodeServlet")
public class checkCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 200;
int height = 100;
// 创建对象 在内存中设置图片(验证码图片对象)
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
// 美化图片
// 设置背景色
Graphics graphics = image.getGraphics();
graphics.setColor(Color.lightGray);
graphics.fillRect(0,0,width,height);
// 画边框
graphics.setColor(Color.BLUE);
graphics.drawRect(0,0,width-1,height-1);
// 设置验证码字符集
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 设置字符样式
graphics.setColor(Color.red);
graphics.setFont(new Font("Arial",Font.ITALIC,25));
// 生成角标
Random ran = new Random();
for (int i = 1; i<=4 ; i++) {
// 获取字符的坐标
int index = ran.nextInt(str.length());
// 获取字符
char ch = str.charAt(index);
// 写验证码
graphics.drawString(ch+" ",width/5*i,height/2);
}
// 生成干扰线
graphics.setColor(Color.GREEN);
for (int i = 0; i <15 ; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
graphics.drawLine(x1,x2,y1,y2);
}
// 将图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
}
我从小到大没有什么梦想,一直在路上不问远方,只是衷心希望自己成为一个很厉害的人。你问我什么算厉害,大概就是能有朝一日,保护好我爱的人,赡养好家人。