package com.zit.sevlet;
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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/check")
public class SecurityCode extends HttpServlet {
private int codelength = 4;
private String securitycodes;
private String codes = "abcdefghijkmnpqrstuvwxyz23456789";
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("image/jpeg");
StringBuilder sb = null;
try {
int width = 400;
int heigth = 200;
int linecounts = 50;
int codesnums = 20;
int circlenums = 5;
//设置画布
BufferedImage bi = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(Color.white);
g.fillRect(1, 1, width - 2, heigth - 2);
//获取随机验证码
Random r = new Random();
sb = new StringBuilder();
for (int i = 1; i <= codelength; i++) {
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.setFont(new Font("微软雅黑", 0, r.nextInt(50) + 80));
char c = codes.charAt(r.nextInt(codes.length()));
sb.append(c);
g.drawString(c + "", 80 * i, r.nextInt(50) + 100);
}
HttpSession session=req.getSession();
session.setAttribute("codes",sb.toString());
//设置干扰线
for (int i = 1; i <= linecounts; i++) {
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(100) + 50));
g.drawLine(r.nextInt(width), r.nextInt(width), r.nextInt(width), r.nextInt(width));
}
// 设置干扰字母
for (int i = 0; i < codesnums; i++) {
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(80) + 30));
g.setFont(new Font("微软雅黑", 0, r.nextInt(50) + 30));
char d = codes.charAt(r.nextInt(codes.length()));
g.drawString(d + "", 20 * (i + 1) + r.nextInt(120), r.nextInt(100) + 70);
}
//设置干扰圆
for (int i = 0; i < circlenums; i++) {
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(50) + 10));
int w = r.nextInt(50) + 30;
g.fillOval(60 * (i + 1), r.nextInt(100) + 50, w, w);
}
ImageIO.write(bi,"jpg",resp.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
public String getSecuritycodes() {
return securitycodes = getCodes();
}
public void setSecuritycodes(String securitycodes) {
this.securitycodes = securitycodes;
}
public int getCodelength() {
return codelength;
}
public void setCodelength(int codelength) {
this.codelength = codelength;
}
public String getCodes() {
return codes;
}
public void setCodes(String codes) {
this.codes = this.codes;
}
}
jsp 页面获取验证码图片
<img src="/check" width="90" height="38" onclick="this.src='/check?'+new Date()" class="ai"/>