一、--------------------------------------------------------------------------login.jsp----------------------------
<p class="login-input login-input-2">
<span class="glyphicon"><i class="glyphicon glyphicon-option-horizontal icon-i"></i></span>
<input type="text" name="j_captcha" class="input-small" id="yanzheng" placeholder="请输入验证码">
</p>
<span style="margin-left:5px" class="validatecode">
<a href="#" onclick="refreshCaptcha();">
<img id="randomcode_img" src="/validatecode" title="点击换一张" />
</a>
</span>
function refreshCaptcha() {
$('#randomcode_img').hide().attr('src','/validatecode?' + Math.floor(Math.random()*100)).fadeIn();
}
二、--------------------------------------------------------------------------controller------------------------------
@RequestMapping(value = "/validatecode", method = RequestMethod.GET)
public String generateCaptchaImage() {
return "/admin/auth/validatecode";
}
三、--------------------------------------------------------------------------validatecode.jsp-------------------
<%@ page language ="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import ="java.util.Random"%>
<%@ page import ="java.io.OutputStream"%>
<%@ page import ="java.awt.Color"%>
<%@ page import ="java.awt.Font"%>
<%@ page import ="java.awt.Graphics"%>
<%@ page import ="java.awt.image.BufferedImage"%>
<%@ page import ="javax.imageio.ImageIO"%>
<%@ page import="com.google.code.kaptcha.Constants" %>
<%
int width = 60;
int height = 32;
//create the image
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// set the background color
g.setColor(new Color(0xeeeeee));
g.fillRect(0, 0, width, height);
// draw the border
g.setColor(Color.gray);
g.drawRect(0, 0, width - 1, height - 1);
// create a random instance to generate the codes
Random rdm = new Random();
String hash1 = Integer.toHexString(rdm.nextInt());
// System.out.print(hash1);
// make some confusion
for (int i = 0; i < 50; i++) {
int x = rdm.nextInt(width);
int y = rdm.nextInt(height);
g.drawOval(x, y, 0, 0);
}
// generate a random code
String capstr = hash1.substring(0, 4);
//将生成的验证码存入session
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capstr);
g.setColor(new Color(0, 153, 255));
g.setFont(new Font("Arial", Font.BOLD, 22));
g.drawString(capstr, 8, 24);
g.dispose();
//输出图片
response.setContentType( "image/jpeg");
out.clear();
out = pageContext.pushBody();
OutputStream strm = response.getOutputStream();
ImageIO.write(image, "jpeg", strm);
strm.close();
%>