用第三方jar生成验证码

用kaptcha生成验证码:

package net.gplatform.sudoor.server.captcha.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 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;

/**
 * This class is used to generate image. The image config is in common-config-sudoor.xml.
 * 
 * Validation In Application :
	protected void validateCaptcha(
					HttpServletRequest request,
					Object command,
					Errors errors) throws Exception {
			String captchaId = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
			String response = ((RegistrationVO) command).getCaptchaResponse();
	
			if (log.isDebugEnabled()) {
					log.debug("Validating captcha response: '" + response + "'");
			}
	
			if (!StringUtils.equalsIgnoreCase(captchaId, response)) {
					errors.rejectValue("captchaResponse", "error.invalidcaptcha",
									"Invalid Entry");
			}
	}

 * 
 * @author xufucheng
 *
 */

@Controller
public class CaptchaImageCreateController {
        private Producer captchaProducer = null;
        
        @Autowired
        public void setCaptchaProducer(Producer captchaProducer) {
                this.captchaProducer = captchaProducer;
        }

        @RequestMapping("/sudoor/captcha-image.html")
        public ModelAndView handleRequest(
                        HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
                // Set to expire far in the past.
                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
                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;
        }
}

验证方法:

package net.gplatform.sudoor.server.captcha.model;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.google.code.kaptcha.Constants;

@Component
public class CaptchaValidator {
	public boolean validate(HttpServletRequest request) {
		String captchaFromSession = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		String captchaFromPage = request.getParameter("_captcha");

		if (StringUtils.equalsIgnoreCase(captchaFromSession, captchaFromPage)) {
			return true;
		}
		return false;

	}
}

 

 HTML:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
	  xmlns:social="http://spring.io/springsocial"
	  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	  layout:decorator="layout">
	<head>
		<title>用户登录</title>
	<script type="text/javascript">
		 function refresh(obj) {  
		        obj.src = "/obiz/app/sudoor/captcha-image.html?"+Math.random();  
		    } 
		</script>
	</head>
	<body>
		<div id="content" layout:fragment="content">
		     <p><span style="color:red" th:text="${errorMsg}">13 February 2011</span></p>
			<form action="#" method="POST" th:action="@{/app/account/login}">
			<p>
				登录名:<input name ="username" type="text"></input>
			</p>
			<p>
				密码:<input name="password" type="password"></input>
			</p>
			<p>
			</p>
			<p>
				验证码:<input name="_captcha" type="text"></input>
				<img alt="验证码" style="cursor:pointer"  οnclick="javascript:refresh(this);"  src="/obiz/app/sudoor/captcha-image.html"></img>
			</p>
			<p>
				<a href="">忘记登录密码?</a>
			</p>
			<p>
				<button type="submit" style="cursor:pointer">登录</button>
			</p>
			
			
			</form>
		</div>	
	</body>
</html>

 

 

 这也有个比较详细的介绍:

http://stone02111.iteye.com/blog/1688195

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值