使用HttpResponse来写验证码

/ java / 70浏览

Servlet:

package top.lhhstudy.servlet;

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 ImageServlet 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 graphics = (Graphics2D) image.getGraphics();

        //设置图片背景颜色
        graphics.setColor(Color.white);
        graphics.fillRect(0,0,80,20); //填充矩形

        //给图片写入数据
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(makeNum(),0,20);

        //告诉浏览器,这个请求的打开方式
        resp.setContentType("image/jpeg");

        //网站的缓存,不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        //把图片写给浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //生成随机数
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999 + 1) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <7-num.length() ; i++) {
            sb.append("0");
        }
        num = sb.toString()+num;
        return num;
    }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">
        <servlet>
            <servlet-name>fileServlet</servlet-name>
            <servlet-class>top.lhhstudy.servlet.FileServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>fileServlet</servlet-name>
            <url-pattern>/fileServlet</url-pattern>
        </servlet-mapping>

        <servlet>
            <servlet-name>imageServlet</servlet-name>
            <servlet-class>top.lhhstudy.servlet.ImageServlet</servlet-class>
        </servlet>

        <servlet-mapping>
            <servlet-name>imageServlet</servlet-name>
            <url-pattern>/imageServlet</url-pattern>
        </servlet-mapping>
</web-app>
站长统计代码