页面
<img src="" title="看不清?换一张" class="popImg" id="img" />
js
//获取验证码
function changeValidateCode() {
var timenow = new Date().getTime();
$("#img").attr('src', '/verifyCode?d=' + timenow);//页面img标签的src属性
//verifyCode 后台方法 加时间戳防止缓存
}
java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.Random;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class VerifyCodeController {
private static final long serialVersionUID = 1L;
private ByteArrayInputStream inputStream;
@RequestMapping("verifyCode")
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
int width = 60;
int height = 28;
BufferedImage image = new BufferedImage(width, height, 1);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", 1, 18));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
UUID uId = UUID.randomUUID();
String sRand = uId.toString().substring(0, 5);
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(sRand, 4, 22);
// contrller 获取session
request.getSession().setAttribute("verifyCode", sRand);
g.dispose();
// 把图片写到输出流中
// 字节数组输出流在内存中创建一个字节数组缓冲区,所有发送到输出流的数据保存在该字节数组缓冲区中
ServletOutputStream out = response.getOutputStream();
// 返回一个 ImageOutputStream,它将其输出发送到给定 Object
ImageOutputStream imageOut = ImageIO.createImageOutputStream(out);
ImageIO.write(image, "JPEG", imageOut);
imageOut.close();
}
private Color getRandColor(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);
}
public void setInputStream(ByteArrayInputStream inputStream) {
this.inputStream = inputStream;
}
public ByteArrayInputStream getInputStream() {
return this.inputStream;
}
}