[转载]用servlet写的一个验证码的例子

本文介绍了一种使用Java生成和验证验证码的方法。通过创建自定义的Servlet,可以生成包含随机数字的图片验证码,并通过session存储生成的验证码字符串进行验证比对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天想写一个验证码,想写带边框的。

不过上网找到一个更不错的验证码

效果为:

-------------------------------验证码生成页--------------------------------------------------

import java.io.*;
import java.net.*;


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

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;


/**
 *
 * @author
 */
public class ValidateView extends HttpServlet {

    public ValidateView (){
        try {
            jbInit();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
   
    private static final String CONTENT_TYPE = "text/html; charset=utf-8";
   
    @Override
    public void init () throws ServletException{
       
    }
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       
        //首先设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
       
        //定义图片的宽度和高度
        int width = 90, height = 40;
       
        //创建一个图形对象
        BufferedImage image = new BufferedImage(width, height,
                                                BufferedImage.TYPE_INT_BGR);
       
        //得到图像的环境对象
        Graphics g = image.createGraphics();
       
        //用随机颜色填充图形背景
        Random random = new Random();
        g.setColor(getRandColor(180, 250));
        g.fillRect(0, 0, width, height);
        for (int i = 0; i < 5; i++){
            g.setColor(getRandColor(50, 100));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.drawOval(x, y, 4, 4);
        }
       
        //设置字体 Font(String name, int style, int size)
        g.setFont(new Font("", Font.PLAIN,40));
       
        String sRand = ""; //随机字符串
        //生成四个随机字符
        for (int i = 0; i < 4; i++){
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
           
            //生成随机颜色
            g.setColor(new Color(20 + random.nextInt(80),
                                 20 + random.nextInt(100),
                                 20 + random.nextInt(90)));
           
            //将随机数字画在图像上
            g.drawString(rand, (17 + random.nextInt(3)) * i + 8, 34);
           
            //生成干扰线
            for (int j = 0; j < 12; j++){
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                int x1 = random.nextInt(9);
                int y1 = random.nextInt(9);
                g.drawLine(x, y, x + x1, y + y1);
            }
        }
       
        ServletContext context = getServletContext();
        context.setAttribute("randomNum", sRand);
       
        //将生成的随机字符串写入session
        request.getSession().setAttribute("randCode", sRand);
       
        //使图像生效
        g.dispose();
       
        //输出图像到页面
        ImageIO.write(image, "jpeg", response.getOutputStream());
    }

    /** *//**
     * 产生一个随机的颜色
     * @param fc front color 前景色
     * @param bc background color 背景色
     * @return
     */
    public Color getRandColor (int fc, int bc){
        Random random = new Random();
       
        if (fc > 255){
            fc = 255;
        }
        if (bc > 255){
            bc = 255;
        }
       
        int red = fc + random.nextInt(bc - fc);
        int green = fc + random.nextInt(bc - fc);
        int blue = fc + random.nextInt(bc - fc);
       
        return new Color(red, green, blue);
    }
   
    private void jbInit() throws Exception{
       
    }
}

----------------------------------------------------------- 验证码显示页index.jsp----------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>用户登录</title>
</head>
<body>
<form name="form1" method="post" action="CheckCode">
    验证码:
      <input name="randCode" type="text"/>
      <img alt="" src="ValidateView" height="25" width="60"/>
     <input name="submit" type="submit" value="submit" />
</form>
</body>
</html>

----------------------------------------------------------------------------验证码调用的servlet--------------------------

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CheckCode extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{

        this.doPost(request, response);
    }
   
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{

        ServletContext context = getServletContext();
       
        //获得当前session中的验证码
        Object codeCurrent = context.getAttribute("randomNum");
       
        //获得用户输入的验证码
        String codeInput = request.getParameter("randCode");
       
        if (codeInput.equals(codeCurrent)){           
            response.sendRedirect("same.jsp");   
        } else{           
            response.sendRedirect("different.jsp");
        }
    }

}


    // </editor-fold>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值