首页 > 代码库 > SpringMvc kaptcha2

SpringMvc kaptcha2

添加 kaptcha-2.3.2.jar

springMvc中注册

<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">        <property name="config">            <bean class="com.google.code.kaptcha.util.Config">                <constructor-arg>                    <props>                        <prop key="kaptcha.border">yes</prop>                        <prop key="kaptcha.border.color">105,179,90</prop>                        <prop key="kaptcha.textproducer.font.color">blue</prop>                        <prop key="kaptcha.textproducer.font.size">30</prop>                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>                        <!--<prop key="kaptcha.textproducer.char.string">拉三等奖水电费和煽风点火收到货付款</prop> 默认为abcde2345678gfynmnpwx-->                        <prop key="kaptcha.textproducer.char.length">4</prop>                        <prop key="kaptcha.image.width">110</prop>                        <prop key="kaptcha.image.height">35</prop>                        <prop key="kaptcha.session.key">valicode</prop>                        <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>                         <!-- <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop> -->                    </props>                </constructor-arg>            </bean>        </property>    </bean>

 

jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML><html>  <head>  <script src="<%=basePath%>resources/js/jquery-3.1.1.min.js"></script>  <script type="text/javascript">    function checkmcode(){    var mcode = $("#mcode").val();    $.ajax({     /*    async : false,        cache : false, */        type : POST,        url : <%=basePath %>/kaptcha/checkmCode,// 请求的action路径        data:{"mcode":mcode},//参数        dataType: "json",           success : function(data){         if(data.success){       $("#searchResult").html(data.msg);    }else{       $("#searchResult").html("出现错误:" + data.msg);    }        },          error: function(jqXHR){                    alert("发生错误:" + jqXHR.status);              },                });}     </script>    <base href="<%=basePath%>">        <title>My JSP ‘kaptcha_jsp.jsp‘ starting page</title>  </head>    <body>    验证码:  <input  id="mcode" name="mcode" value="" class="hst2"   style="vertical-align:middle"/>  <button onclick="checkmcode()" >验证</button>    <img id="img"  style="vertical-align:middle" alt="验证码"  src="<%=basePath %>kaptcha/getKaptchaImage"     onclick="this.src=http://www.mamicode.com/‘kaptcha/getKaptchaImage?e=‘+new Date()"/>    <img id="mcodecheck" src="" alt=""  style="vertical-align:middle"/>    <p id="searchResult"></p>  </body>  </html>

controller

package com.dr.controller;import java.awt.image.BufferedImage;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.json.JSONException;import org.springframework.beans.factory.annotation.Autowired;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;import org.springframework.web.servlet.ModelAndView;import com.dr.domain.Log;import com.google.code.kaptcha.Constants;import com.google.code.kaptcha.Producer;import com.google.gson.Gson;import com.google.gson.JsonObject;@Controller@RequestMapping("kaptcha")public class Kaptcha {                 @Autowired        private Producer captchaProducer;        @RequestMapping("input")        public String input(){            return "kaptcha_jsp";                    }             @RequestMapping("getKaptchaImage")        public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {            HttpSession session = request.getSession();            String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);            System.out.println("******************验证码是: " + code + "******************");                         response.setDateHeader("Expires", 0);            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");            response.addHeader("Cache-Control", "post-check=0, pre-check=0");            response.setHeader("Pragma", "no-cache");            response.setContentType("image/jpeg");            String capText = captchaProducer.createText();            session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);                         BufferedImage bi = captchaProducer.createImage(capText);            ServletOutputStream out = response.getOutputStream();            ImageIO.write(bi, "jpg", out);            try {                out.flush();            } finally {                out.close();            }            return null;        }                @RequestMapping(value="checkmCode",produces = {"text/javascript;charset=UTF-8"},method=RequestMethod.POST)        public  @ResponseBody String checkCode(HttpServletRequest request,String mcode) throws JSONException{             System.out.println("要校验的验证码:"+mcode);             JsonObject js=new JsonObject();             Log log=new Log();             if(((String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY)).equals(mcode)){                 System.out.println("true");                log.setMsg("成功");                log.setSuccess(true);                js.addProperty("msg","成功");                js.addProperty("success",true);             }else {                                     log.setMsg("失败");                    log.setSuccess(false);                    js.addProperty("msg","失败");                    js.addProperty("success",false);            }             Gson gson=new Gson();                   System.out.println( gson.toJson(log));      System.out.println( js.toString());            /*return gson.toJson(log);*/      return js.toString();    }}

 

SpringMvc kaptcha2