spring mvc实现登录验证码

一、实现图形验证码的基础类

VerifyCodeUtils.java,这个类是从网上摘抄的~

package com.comp.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCodeUtils{

    //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符,以及占用太宽的字符W
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVXYZ";
    private static Random random = new Random();

    /**
     * 使用系统默认字符源生成验证码
     * @param verifySize    验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize){
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }
    /**
     * 使用指定源生成验证码
     * @param verifySize    验证码长度
     * @param sources   验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources){
        if(sources == null || sources.length() == 0){
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for(int i = 0; i < verifySize; i++){
            verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成随机验证码文件,并返回验证码值
     * @param w
     * @param h
     * @param outputFile
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 输出随机验证码图片流,并返回验证码值
     * @param w
     * @param h
     * @param os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定验证码图像文件
     * @param w
     * @param h
     * @param outputFile
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
        if(outputFile == null){
            return;
        }
        File dir = outputFile.getParentFile();
        if(!dir.exists()){
            dir.mkdirs();
        }
        try{
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch(IOException e){
            throw e;
        }
    }

    /**
     * 输出指定验证码图片流
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for(int i = 0; i < colors.length; i++){
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h-4);

        //绘制干扰线
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        float yawpRate = 0.05f;// 噪声率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使图片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h-4;
        Font font = new Font("Algerian", Font.PLAIN, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for(int i = 0; i < verifySize; i++){
            //AffineTransform affine = new AffineTransform();
            //affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
            //g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        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);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                            + (6.2831853071795862D * (double) phase)
                            / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                            + (6.2831853071795862D * (double) phase)
                            / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }
}

二、Controller类的实现

controller类的代码:

    @RequestMapping(value="verifyCode", method = RequestMethod.GET)
    public void verifyCode(Model model, Req req,HttpServletRequest request,HttpServletResponse response) {
        //response.setContentType("img/jpeg");
        try {
            OutputStream outputStream=response.getOutputStream();
            int w = 200, h = 80;
            String code = VerifyCodeUtils.generateVerifyCode(4);
            VerifyCodeUtils.outputImage(w, h, outputStream, code);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

注意看,我把

response.setContentType("img/jpeg");

这句注掉了,添加这句话的话,在浏览器中打开,不是查看图片,而是下载图片。去掉就不会下载了,网上的内容真是误人子弟。

不过加上的话,在jsp页面里面通过img标签显示图片也是没有问题的。

三、显示图片

在jsp页面显示这个图片:

<img src="user/verifyCode">

我这篇文章并没有完整的实现验证码,但是已经把最重要的生成验证码图片的功能实现了,想在登录的时候实现验证码功能,还需要把剩下的流程功能实现,我这里就不再累述了。

时间: 2024-08-06 20:02:31

spring mvc实现登录验证码的相关文章

基于spring mvc的图片验证码实现

基于spring mvc的图片验证码实现 标签: springmvcspring mvc验证码验证码验证 2016-01-28 10:49 8015人阅读 评论(4) 收藏 举报  分类: 表单处理 版权声明:本文为博主原创文章,未经博主允许不得转载. 本文实现基于spring mvc的图片验证码,分后台代码和前端页面的展现以及验证码的验证. 首看后台实现代码: @RequestMapping({"authCode"}) public void getAuthCode(HttpServ

Spring MVC过滤器-登录过滤

以下代码是继承OncePerRequestFilter实现登录过滤的代码: /**  *  * @author geloin  * @date 2012-4-10 下午2:37:38  */ package com.test.spring.filter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.FilterChain; import javax.servlet.ServletExce

Spring 系列,第 3 部分: 进入 Spring MVC

在 Spring 系列 的第 3 部分中,我介绍 Spring MVC 框架.就像在以前的文章中一样,我用银行示例介绍如何建模和构建简单的应用程序.示例应用程序包含了已经学过的一些技术(例如依赖注入),但是主要演示 Spring MVC 的特性. 在开始之前,请 下载这篇文章的源代码.请参阅 参考资料 访问 Spring 框架和 Tomcat 5.0,运行示例需要它们. Spring MVC 框架 Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块.使用 Spring 可插入的

spring mvc 4.3.2 + mybatis 3.4.1 + mysql 5.7.14 +shiro 幼儿园收费系统 之 登录

如标题,用spring mvc 4.3.2+mybatis 3.4.1 + mysql 5.7.14 +shiro 开发了一个用于幼儿园的管理系统. 功能模块 包括 账号,角色,权限管理. 幼儿档案管理, 幼儿收费管理等. 权限方面采用了shiro的权限控制,感觉还是蛮强大的.我的理念是 简单,够用就好. 前端框架是基于H-ui.admin的模板来开发的.这个模板用起来还是蛮方便的,适合对前端不是很熟的人采用,可以达到专业的效果.赞一个. 先截个图 实现要点,前端用js把密码用md5加密后传给后

Spring MVC 中使用 Google kaptcha 验证码

验证码是抵抗批量操作和恶意登录最有效的方式之一. 验证码从产生到现在已经衍生出了很多分支.方式.google kaptcha 是一个非常实用的验证码生成类库. 通过灵活的配置生成各种样式的验证码,并将生成的验证码字符串放到 HttpSession 中,方便获取进行比较. 本文描述在 spring mvc 下快速的将 google kaptcha 集成到项目中(单独使用的话在 web.xml 中配置 KaptchaServlet). 1.maven 依赖 官方提供的 pom 无法正常使用,使用阿里

Spring MVC登录注册以及转换json数据

项目结构; 代码如下: BookController package com.mstf.controller; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.jackson.map.ObjectMapper; import com.mstf.

Spring MVC 使用kaptcha生成验证码

Spring MVC 使用kaptcha生成验证码 1.下载kaptcha-2.3.2.jar(或直接通过该文章附件下载) http://code.google.com/p/kaptcha/downloads/list kaptcha-2.3.2-jdk14.jar kaptcha-2.3.2.jar ? 向spring.xml中添加bean <bean id="captchaProducer" class="com.google.code.kaptcha.impl.D

Spring MVC +MyBatis +MySQL 简单的登录查询 Demo 解决了mybatis异常

忙活了大半天,饭也没顾得上吃,哎许久不动手,一动手就出事,下面请看今天的重头戏,额吃个饭回来再发了! 1.整体结构 2.准备工作 数据库: --Mysql 5.6 创建数据库 wolf CREATE DATABASE wolf; 创建用户表 user create table user( id int  AUTO_INCREMENT  primary key, name varchar(25) not null, pwd varchar(20) not null, create_time dat

patchca整合Spring MVC生成超炫的验证码

官方的色调单一,随机色也不随机,黑不拉几的,很难看. 为此做了扩展实现,并整合了spring mvc,生成的验证码漂亮多了. 官网: http://code.google.com/p/patchca/ 官方效果: 下面是我整合到spring并修扩展后的效果: package com.lavasoft.ntv.web; import org.patchca.color.ColorFactory; import org.patchca.filter.predefined.*; import org.