1、简介
登录模块新增验证码验证功能。
注意:验证码的具体验证通过filter实现,理论上也可以通过拦截器interceptor实现。但是实际使用时过滤器(interceptor)和security不是很兼容,过滤器会被覆盖。因此建议使用filter。
页面如下图所示
流程:
- 登录页面访问验证码Controller,随机生成验证码存于session,并返回验证码图片在登录页面显示。
- 登录页面输入验证码,密码,以及用户名等信息并点击提交。
- 自定义的验证码filter对登录页面提交的表单(meath=post url=/login)进行过滤。验证是否有验证码以及是否与后台session存的验证码一致。
- 若一致则通过继续走流程。若不一致则停止并重定向到登录页面。
2、使用
2.1maven
maven 新增google.code.kaptcha依赖
<dependency>
<groupId>com.google.code.kaptcha</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3</version>
</dependency>
2.2spring.xml
spring配置文件新增验证码生成器bean,该bean主要配置生成的验证码样式。(CaptchaImageCreateController会引入该bean用于生成验证码图片。)
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg>
<props>
<prop key="kaptcha.border">no</prop>
<prop key="kaptcha.border.color">105,179,90</prop>
<prop key="kaptcha.textproducer.font.color">red</prop>
<prop key="kaptcha.image.width">250</prop>
<prop key="kaptcha.textproducer.font.size">80</prop>
<prop key="kaptcha.image.height">90</prop>
<prop key="kaptcha.session.key">code</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
2.3验证码生成Controller
此Controller用于生成相关的验证码图片,并把验证码存于session中。
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
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 javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
/**
* <p class="detail">
* 功能:生成验证码
* </p>
*
* @author huanghuizhou
* @ClassName Captcha image create controller.
* @Version V1.0.
* @date 2018.03.07 13:39:40
*/
@Controller
public class CaptchaImageCreateController {
private Producer captchaProducer = null;
@Autowired
public void setCaptchaProducer(Producer captchaProducer) {
this.captchaProducer = captchaProducer;
}
@RequestMapping("/captcha-image")
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
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;
}
}
2.4web.xml新增验证码filter
该filter对登录页面提交的表单(meath=post url=/login)进行过滤。验证是否有验证码以及是否与后台session存的验证码一致。
web.xml假如下面配置
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.gttown.boss.pbc.filter.LoginPostFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/login</url-pattern>
</filter-mapping>
2.5自定义的验证码filter
import com.google.code.kaptcha.Constants;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginPostFilter implements Filter {
private static final Logger logger = Logger.getLogger(LoginPostFilter.class);
String captchaFieldName = "captcha";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (!RequestMethod.POST.name().equals(((HttpServletRequest) servletRequest).getMethod())) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
String requestCaptcha = servletRequest.getParameter(captchaFieldName).toLowerCase();
String genCaptcha = (String) ((HttpServletRequest) servletRequest).getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
logger.info("开始校验验证码,生成的验证码为:" + genCaptcha + " ,输入的验证码为:" + requestCaptcha);
if (!requestCaptcha.equals(genCaptcha)) {
logger.info("验证码错误。");
((HttpServletResponse) servletResponse).sendRedirect(((HttpServletRequest) servletRequest).getContextPath() + "/login?error=captchaError");
return;
}
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
}
}
2.6login页面
<a href="javascript:void(0)">
<img id="captchaImg"src="${pbcDomain}/captcha-image"></a>
<script type="text/javascript">
// 点击图片更换验证码
$(function () {
$("#captchaImg,#captcha-refresh-btn").click(function () {
$("#captchaImg").attr('src', '${pbcDomain}/captcha-image?' + Math.floor(Math.random() * 100));
});
})
</script>