首页 > 代码库 > spring mvc 页面验证码样例

spring mvc 页面验证码样例


验证码类:

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class VerifyCodeServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public VerifyCodeServlet() {

super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {

// 禁止图像缓存,使得单击验证码可以刷新验证码图片

String randSource[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "q", "w", "e", "r", "t", "y", "u",

"i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "z", "x", "c", "v", "b", "n", "m" };

String randStr = "";

HttpSession session = request.getSession();// 获得一个session对象

resp.setHeader("Pragma", "nocache");

resp.setHeader("Cache-Control", "no-cache");

resp.setDateHeader("Expires", 0);

resp.setContentType("image/jpeg");

CreateImageCode vCode = new CreateImageCode(100, 30, 5, 10);

session.setAttribute("verifyCodeFind", vCode.getCode());

vCode.write(resp.getOutputStream());

}

}


jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html lang="zh-CN">

<head>  

    <title>sf</title>

    <form id="formData" method="post" action="${pageContext.request.contextPath }/save">

      <label><span>姓名</span>

        <input id="uName" type="text" name="userName"  />

        </label>

        <label><span>验证码</span>

<input type="text" style="width:100px;height: 30px" name="yzm" id="yzm" tabindex="3" dataType="Limit" min="1"  msg="验证码不能为空" class="i-text"/>

        <img id="changecode" src="http://www.mamicode.com/sf/VerifyCodeServlet?.tmp=0.06781555591097987" style="vertical-align: middle; margin: 0px; cursor: pointer" title="点击更换验证码" border=0 />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        <input type="button" value="http://www.mamicode.com/确认提交" class="tj-btn" id="tj">

    </form>

    <script type="text/javascript">

        $(‘#tj‘).click(function(){

            $.ajax({

                type: ‘POST‘,

url: ‘${pageContext.request.contextPath }/save‘,

data: $(‘#formData‘).serialize(),

dataType:‘json‘,

success: function(data){

                    if(data.result==1){

                        $(‘#formData‘)[0].reset();

$(‘#changecode‘).attr(‘src‘,‘/sf/VerifyCodeServlet?.tmp=‘ + Math.random());

alert(‘提交成功‘);

                    }else{

                        $(‘#changecode‘).click();

alert(data.errorMessage);

    }

                },

                dataType: ‘json‘

            })

        });

        $(‘#changecode‘).click(function(){

            $(this).attr(‘src‘,‘/sf/VerifyCodeServlet?.tmp=‘ + Math.random());

    $(‘#yzm‘).focus().val(‘‘);

});

    </script>

</body>

</html>


控制层:

@Controller

@RequestMapping("/sf")

public class SFController {

@RequestMapping(value = "http://www.mamicode.com/save", method = RequestMethod.POST)

@ResponseBody

public BaseAjaxResponse save(DTO dto,HttpServletRequest request , String yzm) {

BaseAjaxResponse res = new BaseAjaxResponse();

if(StringUtils.isBlank(yzm)){

res.setErrorMessage("验证码不能为空");

return res;

}else if(!yzm.toLowerCase().equals(request.getSession().getAttribute("verifyCodeFind"))){

res.setErrorMessage("验证码错误");

return res;

}else{

request.getSession().setAttribute("verifyCodeFind","");

try {

this.checkedBaggageDamageService.saveOrUpdate(dto, request);

res.setResult(1);

} catch (Exception e) {

e.printStackTrace();

res.setErrorMessage(e.getMessage());

}

}

return res;

}

}


spring mvc 页面验证码样例