关闭

kaptcha验证码插件的使用

标签: kaptcha验证码插件的使用kaptcha验证码插件验证码插件的使用
1073人阅读 评论(3) 收藏 举报
分类:

在SpringMVC的HelloWorld基础下,加入jar

修改web.xml,添加一个servlet

		<!-- kaptcha -->
	<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>

在ioc容器中加入验证码的Bean

   <!-- 验证码的Bean -->
	<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
		<property name="config">
			<bean class="com.google.code.kaptcha.util.Config">
				<constructor-arg type="java.util.Properties">
					<props>
						<prop key="kaptcha.image.width">100</prop>
						<prop key="kaptcha.image.height">50</prop>
						<prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
						<prop key="kaptcha.textproducer.char.string">0123456789abcdefghijklmnopqrstuvwxyz</prop>
						<prop key="kaptcha.textproducer.char.length">4</prop>
					</props>
				</constructor-arg>
			</bean>
		</property>
	</bean>



编写Controller,注意:把上面加入的Bean注入到controller中

package controller;

import org.springframework.stereotype.Controller;
import java.awt.image.BufferedImage;  
import javax.imageio.ImageIO;  
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.servlet.ModelAndView;  
import com.google.code.kaptcha.Constants;  
import com.google.code.kaptcha.Producer;
@Controller
public class YanZhengMaController {
	
	
	@Autowired  
	private Producer captchaProducer;
	
	//提交表单后验证的逻辑过程
	@RequestMapping("/kaptcha.action")
	public String kaptchaSuccess(String checkCode,HttpServletRequest request){
		//从前台获得验证码框中的数据
		String username=checkCode;
		//从session中获得正确的验证码的值
		String str = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		//比较是否相同(相同怎么样,不相同怎么样,我这只是简单的输出,相不相同都跳转的succees.jsp中)
		System.out.println(username+"---------"+str);
		return "success";
	}
	
	
	
	
	
	
	
	 //生成验证码的handler
	 @RequestMapping("/kaptcha.jpg")  
	 //这个requestMapping中的值应该和web.xml中servlet中拦截的url相同,和jsp中表单中显示验证码图片的src相同
	    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {  
	  
	        response.setDateHeader("Expires", 0);  
	        // Set standard HTTP/1.1 no-cache headers.  
	        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
	        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).  
	        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
	        // Set standard HTTP/1.0 no-cache header.  
	        response.setHeader("Pragma", "no-cache");  
	        // return a jpeg  
	        response.setContentType("image/jpeg");  
	        // create the text for the image  
	        String capText = captchaProducer.createText();  
	        // store the text in the session ,把验证码的值存在session中
	        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
	        // create the image with the text  
	        BufferedImage bi = captchaProducer.createImage(capText);  
	        ServletOutputStream out = response.getOutputStream();  
	        // write the data out  
	        ImageIO.write(bi, "jpg", out);  
	        try {  
	            out.flush();  
	        } finally {  
	            out.close();  
	        }  
	        return null;  
	    }  
	
	
	
	
	

	/**
	 * @return the captchaProducer
	 */
	public Producer getCaptchaProducer() {
		return captchaProducer;
	}

	/**
	 * @param captchaProducer the captchaProducer to set
	 */
	public void setCaptchaProducer(Producer captchaProducer) {
		this.captchaProducer = captchaProducer;
	}
	
	
	

}

编写index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
<!-- 引入JQuery -->
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){//页面一加载后执行的函数
	
 
	//给刷新按钮绑定事件,url后面加个参数防止缓存
    $('#kaptchaImage').click(function () {
        $("#kaptcha").attr('src', 'kaptcha.jpg?' + Math.floor(Math.random()*100) );
    })
	
	
	
});
</script>
</head>
<body>

	<form action="kaptcha.action" method="post">
    <input type="text" name="checkCode">
    <img src="kaptcha.jpg" id="kaptcha">
    <input type="button"  id="kaptchaImage"  value="刷新">
    <input type="submit" value="提交">
</form>




</body>
</html>

结果




1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:33720次
    • 积分:734
    • 等级:
    • 排名:千里之外
    • 原创:38篇
    • 转载:0篇
    • 译文:1篇
    • 评论:5条
    文章存档
    最新评论