点击生成动态验证码(工具类)

1.页面

	<!--验证码-->
		    <div class="col-sm-3">
				<img id="vcode" src="/checkCode" style="cursor:pointer">
			</div>
	
	
			<script type="text/javascript">
	                 $("#vcode").click(function(){
	                            $(this).attr("src" , "/checkCode?t=" + new Date());
	                       	 });
			</script>


 //触发图片的点击事件
  $("#vcode").click();

2.后台controller

package com.czxy.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;


@RestController
public class CheckCodeController {

    @RequestMapping("checkCode")
    public ResponseEntity<Void> checkCode(HttpServletResponse response, HttpSession session){
        try {
            int width = 80;
            int height = 32;
            //create the image
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            // set the background color
            g.setColor(new Color(0xDCDCDC));
            g.fillRect(0, 0, width, height);
            // draw the border
            g.setColor(Color.black);
            g.drawRect(0, 0, width - 1, height - 1);
            // create a random instance to generate the codes
            Random rdm = new Random();
            String hash1 = Integer.toHexString(rdm.nextInt());
            // make some confusion
            for (int i = 0; i < 50; i++) {
                int x = rdm.nextInt(width);
                int y = rdm.nextInt(height);
                g.drawOval(x, y, 0, 0);
            }
            // generate a random code
            String capstr = hash1.substring(0, 4);
            session.setAttribute("validateCode", capstr);
            g.setColor(new Color(0, 100, 0));
            g.setFont(new Font("Candara", Font.BOLD, 24));
            g.drawString(capstr, 8, 24);
            g.dispose();
            response.setContentType("image/jpeg");
            OutputStream strm = response.getOutputStream();
            ImageIO.write(image, "jpeg", strm);
            strm.close();

            return ResponseEntity.ok().build();
        } catch (Exception e){
            e.printStackTrace();

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值