package com.itheima.response.body;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet(name = "MyCodeServlet", urlPatterns = "/MyCodeServlet")
public class MyCodeServlet extends HttpServlet {
private Random random = new Random();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*案例:输出验证码图片
* */
//BufferedImage,缓存图片对象
// 构造函数new BufferedImage(width,height,imagetype);
// width,图片宽度
// height,高度
// imagetype,图片的模式
BufferedImage image = new BufferedImage(90, 30, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
Color oriColor = graphics.getColor();
graphics.fillRect(0,0,90,30);
graphics.setColor(Color.red);
graphics.drawRect(0,0,90-1,30-1);
//划干扰线
for(int i=0; i<5; i++){
graphics.setColor(getColor());
graphics.drawLine(random.nextInt(90),random.nextInt(30),random.nextInt(90),random.nextInt(30));
}
//划验证码
String allCode = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
StringBuilder sb = new StringBuilder();
for(int i=0; i<4; i++){
int index = random.nextInt(allCode.length());
char item = allCode.charAt(index);
sb.append(item);//以后验证验证码的时候用
//每个字符随机颜色
graphics.setColor(getColor());
//画到验证码
Font font = new Font(null,0,20);
graphics.setFont(font);
graphics.drawString(item+"",10+(i*20),22);
}
request.getSession().setAttribute("checkCode",sb.toString());
//利用response将缓存图片输出到客户端
ImageIO.write(image, "png", response.getOutputStream());
}
//获取画笔颜色
private Color getColor(){
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r,g,b);
}
}
servlet输出验证码
最新推荐文章于 2023-06-08 21:04:44 发布