java web开发:servlet中图形验证码功能的实现

一 验证码的由来


在web项目开发中,为了防止部分人使用自动工具(如:自动注册机)等进行批量的数据处理,在不同的功能节点部分,添加了验证码进行验证,达到对自动软件的屏蔽效果

最经典的应用如:网站注册图形验证码;接下来,通过java技术,结合servlet实现一个网站注册需要的图形验证码程序,提供大家参考。


二 实现注册页面图形验证码效果


1. 创建web项目:java_servlet_verifyimg



2. 创建自动生成图形验证码的控制器——VerifyImgServlet


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

package com.phome.util;

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

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

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class VerifyImgServlet extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    // 设置随机字符字典。其中不包含0,o,1,I等难以辨认的字符
    public static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8',
            '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a',
            'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',
            'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

    public static Random random = new Random(); // 随机数对象

    public static String getRandomString() {

        StringBuffer buffer = new StringBuffer(); // 字符串缓存
        for (int i = 0; i < 6; i++) // 六次循环获取字符
        {
            buffer.append(CHARS[random.nextInt(CHARS.length)]); // 每次随机取一个字符
        }
        return buffer.toString();
    }

    public static Color getRandomColor() {

        return new Color(random.nextInt(255), random.nextInt(255),
                random.nextInt(255));
    }

    public static Color getReverseColor(Color c) {

        return new Color(255 - c.getRed(), 255 - c.getGreen(),
                255 - c.getBlue());
    }

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

        response.setContentType("image/jpeg"); // 设置输出类型 不可省略

        String randomString = getRandomString(); // 调用生成随机字符串方法获取并接受随机字符串
        request.getSession(true).setAttribute("randomString", randomString); // 将字符串存储到Session中

        int width = 100; // 图片宽度
        int height = 30; // 图片高度

        Color color = getRandomColor(); // 获取随机颜色 用于背景色
        Color reverse = getReverseColor(color); // 反色 用于前景色

        BufferedImage bi = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB); // 创建一个彩色图片
        Graphics2D g = bi.createGraphics(); // 获取绘图对象
        g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16)); // 设置字体
        g.setColor(color); // 设置颜色
        g.fillRect(0, 0, width, height); // 绘制背景
        g.setColor(reverse); // 设置颜色
        g.drawString(randomString, 18, 20); // 绘制随机字符
        for (int i = 0, n = random.nextInt(100); i < n; i++) // 画最多一百个噪音点
        {
            g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1); // 随机噪音点
        }

        ServletOutputStream out = response.getOutputStream(); // 好像是获取输出流

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // 编码器
        encoder.encode(bi); // 对图片进行编码
        out.flush(); // 输出到客户端

    }

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

        this.doGet(request, response);
    }

}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


3. 创建注册控制器——RegistServlet


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

package com.phome.servlet;

import java.io.IOException;

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

/**
 * 注册控制器
 * @author ZuoYi
 *
 */
public class RegistServlet extends HttpServlet{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 从session中获取注册随机验证码
        HttpSession session = req.getSession();
        String randomString = (String)session.getAttribute("randomString");
        
        // 获取用户输入验证码
        String inputRandomString = req.getParameter("randomStr");
        // 判断验证码通过,模拟进行注册
        if (randomString.equals(inputRandomString)) {
            req.setAttribute("resinfo", "恭喜!注册成功!");
        } else {
            req.setAttribute("resinfo", "验证码输入有误,请检查后重新进行注册!");
        }
        // 注册成功或者失败,都跳转到result.jsp页面,查看注册结果。。。
        req.getRequestDispatcher("result.jsp").forward(req, resp);
    }
    
    
}


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


4. 配置servlet


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>simg</display-name>
 
  <!-- 配置用户注册servlet -->
  <servlet>
      <servlet-name>registservlet</servlet-name>
      <servlet-class>com.phome.servlet.RegistServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>registservlet</servlet-name>
      <url-pattern>/regist.action</url-pattern>
  </servlet-mapping>
 
  <!-- 配置图形验证码servlet -->
  <servlet>
      <servlet-name>verifyimg</servlet-name>
      <servlet-class>com.phome.servlet.VerifyImgServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>verifyimg</servlet-name>
      <url-pattern>/verifyimg.action</url-pattern>
  </servlet-mapping>
 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


5. 创建注册视图测试页面——regist.jsp


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  <body>
  <form action="${pageContext.request.contextPath}/regist.action" method="post">
      用户名:<input type="text" name="username"/>
    <br />
      密码:<input type="text" name="password"/>
    <br />
      请输入验证码进行注册:
    <img src="${pageContext.request.contextPath }/verifyimg.action"/>
    <input type="text" name="randomStr"/>
    <br />
    <input type="submit" value="regist"/>      
  </form>
  </body>
</html>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

5.1 创建注册结果页面——result.jsp

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  <body>
  ${requestScope.resinfo }
  </body>
</html>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


6. 测试

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(1)a.打开浏览器,输入测试地址:http://localhost:8080/java_servlet_verifyimg;出现如下图所示页面

 

b.输入注册账号、密码和验证码后点击regist提交

 

c.测试结果,跳转会注册页面,提示注册成功

(2)打开注册页面

输入错误注册码

测试结果页面


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


over!

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 Java 后端代码实现图形验证码的示例: ```java import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; 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; @WebServlet("/captcha") public class CaptchaServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int width = 100; // 验证码图片宽度 int height = 40; // 验证码图片高度 int length = 4; // 验证码位数 String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; // 随机字符集合 // 创建一个随机数生成器 Random random = new Random(); // 创建一个 BufferedImage 对象,用于绘制验证码图片 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取一个 Graphics2D 对象,用于绘制图形 Graphics2D g2d = image.createGraphics(); // 设置背景色 g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, width, height); // 绘制边框 g2d.setColor(Color.BLACK); g2d.drawRect(0, 0, width - 1, height - 1); // 绘制随机字符 g2d.setFont(new Font("Arial", Font.BOLD, 20)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { char c = chars.charAt(random.nextInt(chars.length())); sb.append(c); g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); g2d.drawString(String.valueOf(c), 20 * i + 10, 25); } // 绘制干扰线 for (int i = 0; i < 5; i++) { g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); g2d.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); } // 将生成的验证码字符串存入 Session ,以便后续验证 req.getSession().setAttribute("captcha", sb.toString()); // 关闭 Graphics2D 对象 g2d.dispose(); // 向客户端输出验证码图片 resp.setContentType("image/png"); ServletOutputStream out = resp.getOutputStream(); ImageIO.write(image, "png", out); out.close(); } } ``` 在上述代码,我们通过 `Random` 类生成随机字符和干扰线,然后使用 `Graphics2D` 类将这些元素绘制到一个 `BufferedImage` 对象。最后,我们将生成的验证码字符串存入 Session ,并将验证码图片作为 PNG 格式输出给客户端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值