public String getCheckCode(HttpServletRequest request,HttpServletResponse response) throws Exception {
BufferedImage bufferedImage = new BufferedImage(55, 23, BufferedImage.TYPE_INT_BGR);
Graphics g = bufferedImage.getGraphics();
g.setColor(new Color(247, 247, 247));
g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
Random rand = new Random();
for (int i = 0; i < 10; i++) {
g.setColor(new Color(rand.nextInt(200), rand.nextInt(200), rand.nextInt(200)));
g.drawLine(rand.nextInt(60), rand.nextInt(25), rand.nextInt(60), rand.nextInt(25));
}
StringBuilder code = new StringBuilder();
for (int i = 0; i < 4; i++) {
code.append(rand.nextInt(9));
}
Font f = new Font("Georgia", Font.BOLD, 18);
g.setFont(f);
g.setColor(Color.BLACK);
g.drawString(code.toString(), 1, 18);
g.dispose();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bufferedImage);
InputStream image = new ByteArrayInputStream(bos.toByteArray());
request.getSession().setAttribute("imgcode", code.toString());
ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
return code.toString();
}
------------------------------------
@RequestMapping("/getcheckcode.htm")
public String getcheckcode(HttpServletRequest request,HttpServletResponse response) throws Exception{
CheckCodeUtils checkcode = new CheckCodeUtils();
response.setHeader("Cache-Control", "no-cache,must-revalidate");
response.setCharacterEncoding("UTF-8");
String code = checkcode.getCheckCode(request,response);
return null;
}
-----------------------------------------
<img id="imgCode" align="absMiddle" src="" οnclick="changeimgcode();" alt="看不清,点我换换看啊!" style="cursor:hand;">
function changeimgcode(){
document.getElementById('imgCode').src='$!{request.contextPath}/getcheckcode.htm?'+new Date();
}