java 手写验证码
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
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;
public class Verify extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//每3秒刷新一次浏览器
resp.setHeader("refresh","3");
// 在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
// 得到图片 生成笔
Graphics2D g = (Graphics2D) image.getGraphics();
// 设置背景颜色
g.setColor(Color.white);
// 填充
g.fillRect(0,0,80,20);
// 给图片写数字
g.setColor(Color.red);
g.setFont(new Font(null,Font.BOLD,20));
// 生成随机数
g.drawString(makeNum(),0,20);
// 告诉浏览器图片的形式打开
resp.setContentType("image/jpg");
// 不让网站缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
// 把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNum(){
Random random = new Random();
String num = random.nextInt(99999) + "";
StringBuffer stringBuffer = new StringBuffer();
// 保证一定输出5位,位数不够时,后面补足
for(int i=0;i<5-num.length();i++){
stringBuffer.append("0");
}
num = stringBuffer.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
在web.xml 中配置
<servlet>
<servlet-name>verify</servlet-name>
<servlet-class>Verify</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>verify</servlet-name>
<url-pattern>/verify</url-pattern>
</servlet-mapping>
结果: