基于JavaEE servlet的原生验证码的生成

这篇博客介绍了如何使用JavaEE的servlet生成原生验证码。通过创建动态Web项目,定义servlet,设置背景、边框、随机线条,并生成带有旋转效果的随机字符,最后将验证码保存到session中。
摘要由CSDN通过智能技术生成

1.创建一个动态Web项目:

2.创建一个servlet在一个包名叫:pack1:

 

//源码如下:

package pack1;

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

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;

 
/**
 * Servlet implementation class Check
 */
@WebServlet("/Check")
public class Check extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public Check() {
        super();
    }

    //不能再方法里面
    private static final int Width=120;
    private static final int Height=25;
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建图形
        BufferedImage image=new BufferedImage(Width, Height, BufferedImage.TYPE_INT_BGR);
        Graphics graph=(Graphics) image.getGraphics();
        //设置背景颜色
        setBackground((Graphics2D)graph);
        //设置显示边框
        setBorder((Graphics2D)graph);
        //设置随机线条
        setRandomLine((Graphics2D)graph);
        //生成随机验证码2D是为了让随机数旋转
        //并设置一个接收返回的验证码:
        //后面将利用这个服务器里面的验证码进行对比:
        String ServerCheckCode=setRandomNum((Graphics2D)graph);
        //利用session存储起来:!!!!
        request.getSession().setAttribute("ServerCheckCode", ServerCheckCode);
        //设置头,不要取缓冲!!!
         response.setContentType("image/jpeg");
         response.setDateHeader("expries",-1);
         response.setHeader("Cache-Control","no-cache");
         response.setHeader("Pragma","no-cache");
         ImageIO.write(image, "jpg", response.getOutputStream());
 
        
        //response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    //@2019.03.27 19:50
    //产生验证码后返回验证码:
    private String setRandomNum(Graphics2D graph) {
        //创建一个string Buffer用于存储返回的验证码的每一个数字,后面追加到这个对象的后面
        //说明为什么不用string而用string buffer:
        //注意二者的区别是string buffer的大小是可以改变的,利用其函数可以追加字符:
        //定义string buffer对象:
        StringBuffer bfBuffer=new StringBuffer();
        graph.setColor(new Color(new Random().nextInt(256),new Random().nextInt(256),new Random().nextInt(256)));
        graph.setFont(new Font("宋体",Font.BOLD,20));
        
        String baseString="1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM";
           int x=10;
            //产生四个随机字符
            for (int i = 0; i < 4; i++) {
                int degree= new Random().nextInt()%30;//产生正负30之间的随机数
                //得到每一个验证码字符:
                String ch=baseString.charAt(new Random().nextInt(baseString.length()))+"".toString();//随机获取base单个字符
                //将每一个字符追加到string buffer对象里面:
                bfBuffer.append(ch);
                //旋转
                graph.rotate(degree*Math.PI/180,x,20);//设置旋转角度
                graph.drawString(ch, x, 20);//画出
                graph.rotate(-degree*Math.PI/180,x,20);//设置旋转角度
                x+=30;//字符之间的横向间隔
            }
            //最后返回这个验证码即 buffer这个对象:
            return bfBuffer.toString();
    }

    private void setRandomLine(Graphics2D graph) {
        graph.setColor(new Color(new Random().nextInt(256),new Random().nextInt(256),new Random().nextInt(256)));
        for(int i=0;i<6;i++) {
            int X1=new Random().nextInt(Width);
            int y1=new Random().nextInt(Height);
            int X2=new Random().nextInt(Width);
            int y2=new Random().nextInt(Height);
            
            graph.drawLine(X1, y1, X2, y2);
        }
    }

    private void setBorder(Graphics2D graph) {
        //设置边框颜色:
        graph.setColor(new Color(new Random().nextInt(256),new Random().nextInt(256),new Random().nextInt(256)));
        graph.drawRect(1, 1, Width, Height);
    }

    private void setBackground(Graphics2D graph) {
        //设置背景颜色
        graph.setColor(Color.WHITE);
        graph.fillRect(0, 0, Width, Height);
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值