首先要引入第三方的依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.3</version>
</dependency>
编写生成验证码的Controller
@Controller
public class CaptchaController {
@RequestMapping(value = "/captcha",method = RequestMethod.GET)
public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
//定义图形验证码大小
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(150, 50);
ByteArrayInputStream imageStream = new ByteArrayInputStream(lineCaptcha.getImageBytes());
HttpSession session = request.getSession();
session.setAttribute("captcha", lineCaptcha.getCode());
ServletOutputStream outputStream = response.getOutputStream();
lineCaptcha.write(outputStream);
}
}
在前端页面上获取到验证码
<p class="fieldset">
<label class="image-replace cd-password" for="captcha">验证码</label>
<input class="has-padding has-border" id="captcha" type="text" name="captcha" placeholder="请输入验证码">
<img src="${pageContext.request.contextPath}/captcha" style="vertical-align: bottom">
</p>
之后是自定义一个过滤器来验证用户输入的验证码和生成的验证码是否一致,一致则进行下一步,不一致则返回登录页面
public class CaptchaFilter extends HttpPutFormContentFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// 判断session当中的验证码 与 用户输入的验证码是否一致
// 如果不加判断,它会过滤全部的请求
String uri = request.getRequestURI();
if (uri.contains("/login")) {
String sessionCode = (String) request.getSession().getAttribute("captcha");
String userCode = request.getParameter("captcha");
if (StringUtils.isEmpty(userCode)) {
response.sendRedirect("userLogin");
return;
}
if (!sessionCode.equalsIgnoreCase(userCode)) {
response.sendRedirect("userLogin");
return;
}
}
super.doFilterInternal(request, response, filterChain);
}
}
最后就是让自定义的过滤器要在登录验证之前来执行
<!--配置自己的过滤器-->
<bean id="captchaFilter" class="com.zxl.filter.CaptchaFilter"/>
在登录验证之前生效(在security:http内)
<security:custom-filter ref="captchaFilter" before="FORM_LOGIN_FILTER"/>
效果图