注册 Filter:
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
FilterRegistration.Dynamic verificationCodeFilter = servletContext.addFilter(“verificationCodeFilter”, new VerificationCodeFilter());
verificationCodeFilter.addMappingForUrlPatterns(null, false, “/j_captcha.jpg”);
verificationCodeFilter.addMappingForUrlPatterns(null, false, “/index”);
}
jsp:
<c:url var="loginUrl" value="/index" />
<form action="${loginUrl}" method="post" class="form-horizontal">
<c:if test='${param.verifi != null}'>
<div class="alert alert-success">
<p>验证码错误!</p>
</div>
</c:if>
<label >验证码:</label>
<input name="j_captcha" style="width: 60px" class="form-control" type="text" />
<img id="captchaImg" src="<c:url value='/j_captcha.jpg'/>" />
</div>
</br>
<input type="submit" value="登陆"/>
<script type="text/javascript">
$("#captchaImg").click(function(){
$('#captchaImg').hide().attr(
'src',
'<c:url value="/j_captcha.jpg"/>'
+ '?'+ Math.floor(Math.random() * 100)
).fadeIn();
});
</script>
</form>
VerificationCode :
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* VerificationCode:
*
* dpica
*
*/
public class VerificationCode {
// 宽
private static int WIDTH = 80;
// 高
private static int HEIGHT = 30;
// 验证码数量
private static int NUM = 4;
// 干扰线数量
private static int LINE = 4;
private static char[] SHOWTEXT = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9' };
/**
* 生成随机的验证码
*
* @return
* @throws Exception
*/
public void generator(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Random r = new Random();
// 图片的内存映像
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
// 获得画笔对象
Graphics g = image.getGraphics();
g.setColor(randomColor(200,250));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(new Color(0,0,0));
// 用于存储随机生成的验证码
StringBuffer number = new StringBuffer();
// 绘制验证码
for (int i = 0; i < NUM; i++) {
g.setColor(randomColor(20,200));
int h = (int) ((HEIGHT * 50 / 100) * r.nextDouble() + (HEIGHT * 50 / 100));
g.setFont(new Font(null, Font.BOLD | Font.ITALIC, h));
String ch = String.valueOf(SHOWTEXT[r.nextInt(SHOWTEXT.length)]);
number.append(ch);
g.drawString(ch, i * WIDTH / NUM * 90 / 100, h);
}
// 绘制干扰线
for (int i = 0; i <= LINE; i++) {
g.setColor(randomColor(100,200));
g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH),
r.nextInt(HEIGHT));
}
request.getSession().setAttribute("imageCode", number.toString());
//System.out.println("----VerificationCode----" + number.toString());
g.dispose();
//有用
response.reset();
ImageIO.write(image, "jpeg", response.getOutputStream());
}
private Color randomColor(int fc, int bc) {
Random random = new Random();
if (fc > 255) fc = 255;
if (bc > 255) bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
VerificationCodeFilter :
public class VerificationCodeFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
String code = request.getParameter("j_captcha");
String sessionCode = (String) request.getSession().getAttribute(
"imageCode");
String servletPath = request.getServletPath();
String filterProcessesUrl = "/index";
if (StringUtils.startsWith(servletPath, filterProcessesUrl)) {
if (code.equalsIgnoreCase(sessionCode)) {
chain.doFilter(request, response);
} else {
response.sendRedirect("./login?verifi=true");
return;
}
} else {
try {
//response.sendRedirect("./login?verifi=true");
new VerificationCode().generator(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}