使用response输出随机图片验证码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15783243/article/details/82909770

本项目主要针对于JavaWeb中使用response对象的方法生成一个随机验证码图片,在客户端进行表单注册或者登陆时,需要正确输入随机图片中的数字。

        生成随机图片的类为:

/**
 * 每次更改页面src里面内容的时候,img的图像就会相应的改变
 * 如果src指向的是一个接口,那么每次改变就会自动去调用接口
 * (验证码刷新实现)
 * 管理员验证码
 * 
 * @param response
 *            HttpServletResponse
 * @throws ServletException
 * @throws IOException
 */
@RequestMapping("/captcha.jpg")
public void captcha(HttpServletResponse response) throws ServletException, IOException {
   response.setHeader("Cache-Control", "no-store, no-cache");
   response.setContentType("image/jpeg");

   // 生成文字验证码
   String text = producer.createText();
   // 生成图片验证码
   BufferedImage image = producer.createImage(text);
   // 保存到shiro session
   ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

   ServletOutputStream out = response.getOutputStream();
   ImageIO.write(image, "jpg", out);
}

在HTML中生成一个表单:

<div class="form-group has-feedback">
    <img alt="如果看不清楚,请单击图片刷新!" class="pointer" src="${rc.contextPath}/admin/captcha.jpg" onclick="refreshCode()">
    &nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:;" onclick="refreshCode()">点击刷新</a>
</div>
<script type="text/javascript">
    $(function () {
        if (self != top) {
            top.location.href = self.location.href;
        }
    });

    function refreshCode() {
        $(".pointer").attr("src", "${rc.contextPath}/admin/captcha.jpg?t=" + new Date().getTime());
    }

<script />

每次点击刷新就在后台生成一个验证码图片,同事图片的数字保存到session, 登录时就把验证码 

取出与用户登录时 输入的验证码是否一致,若一致就允许用户登录。

String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
if (!captcha.equalsIgnoreCase(kaptcha)) {
   return R.error("验证码不正确");
}

猜你喜欢

转载自blog.csdn.net/qq_15783243/article/details/82909770