java 代码Springmvc框架结合JS 动态生成随机图形验证码完整案例

版权声明:本文为博主原创文章,如需转载,敬请注明转载链接 https://blog.csdn.net/guobinhui/article/details/80857012

平时我们日常见到的有登录功能的系统都会有图形验证码的识别,现在大多数图形验证码都是通过第三方插件可以生成,那么运用我们平时的Java知识自己动手写一个生成随机图形验证码的案例,是不是很有意思 了,不废话了,直接上代码,快来围观。

首先案例采用的是Springmvc框架的maven项目,在maven项目的pom.xml文件引入权限控制shiro的依赖jar包

<!-- shiro start -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.4.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- end shiro -->

1、后台java代码:

/**
 * Copyright *********有限公司
 */
package com.hoomsun.wealth.cust.app.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 作者:guo bin hui <br>
 * 创建时间:2018年6月29日 <br>
 * 描述:java结合JS 生成动态随机图形验证码
 */
@Controller
@RequestMapping("/test/verificationCode")
public class VerificationCodeController {
	public static final String SESSION_SECURITY_CODE = "imageCode";
	
	@RequestMapping(value = "/generate.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
    public void generate(HttpServletRequest req,HttpServletResponse response){
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        String code = drawImg(output);
        // 将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        session.setAttribute(SESSION_SECURITY_CODE, code);
          //下面权限控制这种写法涉及到过滤器的相关配置,暂时报错,先按照上面的代码理解
//        Subject currentUser = SecurityUtils.getSubject();  
//        Session session = currentUser.getSession();
//        session.setAttribute(, code);        
        try {
            // 将图像输出到Servlet输出流中
            ServletOutputStream out = response.getOutputStream();
            output.writeTo(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	private String drawImg(ByteArrayOutputStream output){
        String code = "";
        for(int i=0; i<4; i++){
            code += randomChar();
        }
        int width = 70;
        int height = 25;
        BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        Font font = new Font("Times New Roman",Font.PLAIN,20);
        Graphics2D g = bi.createGraphics();
        g.setFont(font);
        Color color = new Color(66,2,82);
        g.setColor(color);
        g.setBackground(new Color(226,226,240));
        g.clearRect(0, 0, width, height);
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(code, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = y - ascent;
        g.drawString(code, (int)x, (int)baseY);
        g.dispose();
        try {
            ImageIO.write(bi, "jpg", output);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;
    }
	
	private char randomChar(){
        Random r = new Random();
        String str = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
        return str.charAt(r.nextInt(str.length()));
    }
}

2、前台jsp代码

<div class="item clearfix">
    <label>yanZhengMa</label>
    <div class="inputBox"><input class="yzm" name="YZM" id="YZM" type="text">
    <img src="images/xiajia.png" width="127" height="41" id="codeImg" alt="点击更换" title="点击更换">
    </div>
</div>

3、js代码

<script type="text/javascript">
$(function(){
	changeCode();
    $("#codeImg").bind("click", changeCode);
});
function changeCode() {
    $("#codeImg").attr("src", "test/verificationCode/generate.do?time=" + new Date().getTime());
    $("#YZM").val("");
}
</script>

生成的图形验证码界面如下所示:验证码点击前

验证码点击后



猜你喜欢

转载自blog.csdn.net/guobinhui/article/details/80857012