Servlet实例专题

利用Servlet生成动态验证码

2018-08-21  本文已影响0人  神坛下的我

UseServlet.java

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/user.do")
public class UseServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //设置字符集格式为utf-8
        //req.setCharacterEncoding("UTF-8");
        
        //禁止页面缓存
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "No-cache");
        resp.setDateHeader("Expires", 0);
        //设置响应正文的MIME类型为图片
        resp.setContentType("image/jpeg");
        int width=60,height=20;
        /**
         * 创建一个位于缓存中的图像,宽度为60,高度为20
         * */
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();//获取用于处理图形上下文的对象,相当于画笔
        Random random = new Random();//创建生成随机数的对象
        g.setColor(getRandomColor(200, 250));//设置图像的背景色
        g.fillRect(0, 0, width, height);//画一个矩形,坐标(0,0),宽度为60,高度为20
        g.setFont(new Font("Times New Roman",Font.PLAIN,18));//设定字体格式
        g.setColor(getRandomColor(160, 200));
        for (int i = 0; i < 130; i++) {//产生130条干扰线
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x, y, x+x1, y+y1);//在图像的坐标x,y和坐标x+x1,y+y1之间画干扰线
        }
        String strCode="";
        for (int i = 0; i < 4; i++) {
            String strNumber=String.valueOf(random.nextInt(10));
            strCode=strCode+strNumber;
            //设置字体的颜色
            g.setColor(new Color(15+random.nextInt(120),15+random.nextInt(120),15+random.nextInt(120)));
            g.drawString(strNumber, 13*i+6, 16);//将验证码依次画到图像上,坐标x=13*i+6,y=16
        }
        req.getSession().setAttribute("Code", strCode);//把验证码保存到Session中
        g.dispose();//释放此图像的上下文以及它使用的所有系统资源
        ImageIO.write(image, "JPEG", resp.getOutputStream());//输出JPEG格式的图像
        resp.getOutputStream().flush();
        resp.getOutputStream().close();
        
        
        //req.getRequestDispatcher("index.jsp").forward(req, resp);
        
    }
    
    /**
     * 一个获取随机颜色的方法
     */
    public Color getRandomColor(int fc,int bc){
        Random random = new Random();
        Color randomColor = null;
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        //设置0~255之间的随机数颜色值
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        randomColor = new Color(r,g,b);
        return randomColor;//返回具有指定红色、绿色和蓝色值的不透明的sRGB颜色
    }
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}

index.jsp

    <form action="user.do" method="post">
        <table align="center">
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="name"/></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="pwd"/></td>
            </tr>
            <tr>
                <td>性别:</td>
                <td>
                    <input type="radio" name="sex" value="男"/>男
                    <input type="radio" name="sex" value="女"/>女
                </td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="text" name="age"/></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="text" name="email"/></td>
            </tr>
            <tr>
                <td>验证码:</td>
                <td><img alt="" src="<%=request.getContextPath()%>/user.do"><a href="">换一张</a></td>
            </tr>
            <tr>
                <td>输入验证码:</td>
                <td><input type="text" name="code"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                <input type="submit" value="注册"/>
                <input type="reset" value="重置"/>
                </td>
            </tr>
        </table>
    </form>
33.PNG 34.PNG 35.PNG
上一篇 下一篇

猜你喜欢

热点阅读