生成验证码插件kaptcha的使用(jsp中)

来源:互联网 发布:批量水印制作软件 编辑:程序博客网 时间:2024/06/05 14:40

web。xml的配置

<!-- 生成验证码配置 -->
    <servlet>
        <servlet-name>Kaptcha</servlet-name>
        <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Kaptcha</servlet-name>
        <url-pattern>/kaptcha.jpg</url-pattern>
    </servlet-mapping>   

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'yanzhengma.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>

  </head>
 
  <body>
    <form action="<%=path %>/users/yanzhengma.do">
         <input type="text" name="kaptcha" value="" />
         <img src="kaptcha.jpg" id="kaptchaImage"/>
         <input type="submit" value="提交">
    </form>
    <script type="text/javascript">
        $(function(){
            $('#kaptchaImage').click(function () {
                $(this).attr('src', '<%=basePath%>/kaptcha.jpg?' + Math.floor(Math.random()*100) );
            })
        });
    </script>
    <br /><small>Can't read the image? Click it to get a new one.</small>
  </body>
</html>

后台控制器验证

    @RequestMapping("/yanzhengma.do")
    public String yanzhengma() {
        String kaptchaExpected = (String) request.getSession().getAttribute(
                "key");
        String kaptchaReceived = request.getParameter("kaptcha");
        System.out.println("kaptchaExpected=" + kaptchaExpected + " "
                + "kaptchaReceived=" + kaptchaReceived);
        if (kaptchaReceived == null
                || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) {
            return "error";
        }
        return "ok";
    }

验证码图片使用默认的样式

0 0
原创粉丝点击