杂记(三):jsp添加登录验证码

绪论

杂七杂八,瞎记一下。

一、前端生成

index.jsp 代码

<%@ page language="java" contentType="text/html; charset=utf-8" import="java.util.*"
    pageEncoding="utf-8"%>
<%
    String contextPath = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + contextPath + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <base href="<%=basePath%>">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <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">
<title>验证码展示页面</title>
</head>
<%
    String numberCode = (String)request.getParameter("numberCode");
    String rightcode = (String)session.getAttribute("rightcode");

    if(numberCode != null && rightcode != null){
        if(numberCode.equals(rightcode)){
            out.println("验证码输入正确");
        }else{
            out.println("验证码输入不正确,请重新输入!");
        }
    }
%>
<body>
    <form action="" method="post">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username"/></td>
                <td></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password"/></td>
                <td></td>
            </tr>
            <tr>
                <td>验证码:</td>
                <td><input type="text" name="numberCode"/></td>
                <td><img src="imgNumber.jsp"></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="登录"/></td>
                <td></td>
            </tr>
        </table>
    </form>
</body>
</html>

imgNumber.jsp 代码

<%@ page language="java" contentType="image/jpeg" 
    import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*"
    pageEncoding="utf-8"%>
<%!
    Color getRandColor(int fc, int bc){
        Random random = new Random();
        if(fc > 255){
            fc = 255;
        }
        if(bc < 255){
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);

        return new Color(r, g, b);
    }
%>

<%
    // 设置页面不缓存
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    // 在内存中创建图像
    int width = 60;
    int height = 20;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    // 创建图像
    Graphics g = image.getGraphics();
    // 生成随机对象
    Random random = new Random();
    // 设置背景色
    g.setColor(getRandColor(200, 250));
    g.fillRect(0, 0, width, height);
    // 设置字体
    g.setFont(new Font("Tines Nev Roman", Font.PLAIN, 18));
    // 随机产生干扰线
    g.setColor(getRandColor(160, 200));
    for(int i = 0; i < 255; i++){
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int x1 = random.nextInt(12);
        int y1 = random.nextInt(12);
    }
    // 随机产生验证码,4位数字
    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(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(rand, 13*i + 6, 16);
    }
    session.setAttribute("rightcode", sRand);
    // 图像生效
    g.dispose();
    // 输出图像到页面
    ImageIO.write(image, "JPEG", response.getOutputStream());
    out.clear();
    out = pageContext.pushBody();
%>

运行结果:
这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

二、后端生成

index.jsp 代码

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<% 
    String contextPath = request.getContextPath();

    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + contextPath + "/";
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录页</title>
<script type="text/javascript">

function verificationCode(){
    // 获取时间戳(只有ie某些版本不加时间戳,会发生浏览器缓存)
//  var timestamp = (new Date()).valueOf();
//  var timestamp = new Date().getTime();

    $("#imgCode").attr("src", "<%=contextPath %>/system/imgNumber?timestamp=" + (new Date()).valueOf());
}
</script>
</head>
<body>
<div>
    <table>
        <tr>
            <td>验证码:</td>
            <td><input type="text" id="putNumber" name="putNumber" maxlength="8"></td>
            <td><img id="imgCode" src="imgNumber" onclick="verificationCode()"></td>
        </tr>
    </table>
</div>
</body>
</html>

控制层访问方法

/**
 * 获取验证码图片
 * @param request
 * @param response
 * @throws IOException
 */
@RequestMapping("imgNumber")
@ResponseBody
public void toImgNumber(HttpServletRequest request, HttpServletResponse response) throws IOException{
    VerificationCode.outputVerificationCode(request, response);
}

验证码生成工具类

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.ServletOutputStream;
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 VerificationCode {

    // 随机字符字典
    private static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
            'h', 'i', 'j', 'k', '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' };

    // 随机数
    private static Random random = new Random();

    /*
     * 获取6位随机数
     */
    private static String getRandomString() {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return buffer.toString();
    }

    /*
     * 获取随机数颜色
     */
    private static Color getRandomColor() {
        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
    }

    /*
     * 获取某颜色的反色
     */
    private static Color getReverseColor(Color c) {
        return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
    }

    /*
     * 生成验证码
     */
    public static void outputVerificationCode(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("image/jpeg");
        String randomString = getRandomString();
        request.getSession(true).setAttribute("imgNumber", randomString);

        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("Times New Roman", 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);
        }

        // 转成JPEG格式
        ServletOutputStream out = response.getOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(bi);
        out.flush();
    }
}

运行结果:

这里写图片描述

(若有什么错误,请留言指正,3Q)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值