转贴请标明出处:http://blog.csdn.net/kouwoo/article/details/42675201
springmvc的配置就不详细说了,这里就把关键地方的代码贴出来
code.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function refresh(obj) {
var w = "${w}";
obj.src = w + "/im.html?" + Math.random(); //加个Math.random();为了不让浏览器有缓存
$("#validatecode").attr("value","");
}
</script>
</head>
<body>
<form action="validate.html" method="post">
<table>
<tr>
<td>验证码:</td>
<td>
<input type="text" id="validatecode" name="validatecode"/>
</td>
<td>
<img style="cursor: pointer;" οnclick="refresh(this);"
src="${w}/im.html" title="点击刷新验证码" />
</td>
<td><input type="submit" value="确定"/></td>
</tr>
</table>
</form>
</body>
</html>
CodeController.java
package net.spring.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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.RequestParam;
import com.cx.web.common.util.RandomValidateCode;
@Controller
public class CodeController {
@RequestMapping(value = "code", method = RequestMethod.GET)
public String code(HttpSession session, HttpServletRequest request) {
session.setAttribute("w", request.getContextPath());
return "code";
}
/**
* 获取验证码
* @param response
* @param request
*/
@RequestMapping("im")
public void validationImg(HttpServletResponse response,
HttpServletRequest request) {
response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
response.setHeader("Pragma", "No-cache");// 设置响应头信息,告诉浏览器不要缓存此内容
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
RandomValidateCode randomValidateCode = new RandomValidateCode();
try {
randomValidateCode.getRandcode(request, response);// 输出图片方法
} catch (Exception e) {
}
}
/**
* 判断验证码是否正确
* @param validatecode
* @param session
* @return
*/
@RequestMapping(value ="validate",method = RequestMethod.POST)
public String validate(@RequestParam String validatecode,HttpSession session){
// 取得 session 中的 code
String validateC = (String) session.getAttribute(RandomValidateCode.RANDOMCODEKEY);
if (validatecode == null || "".equals(validatecode)) {
// 输入的验证码为空
// TODO
}
if (!validateC.equals(validatecode.toUpperCase())) {
// 输入的验证码不正确
// TODO
}
return null;
}
}
效果图