前端代码:
<img id="img" src="/img" /><a href="#" onclick="javaSpcript:change()">看不清</a>//验证码的图片标签以及切换验证码的标签
<script type="text/javascript">
function change(){
document.getElementById('img').src="/img?r="+new Date();//切换验证码的方法,因为浏览器自带缓存,所以需要添加new Data()重新向服务器发送请求
}
</script>
后端代码:
@RequestMapping(path = "/img")
public void img(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("image/jpg");//设定返回的头文件,指定返回对象类型
//画验证码图片
BufferedImage buffer = new BufferedImage(70, 35, BufferedImage.TYPE_INT_ARGB);创建缓存
Random r = new Random();
Graphics g = buffer.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, 70, 35);
String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
String code = "";
for (int i = 0; i < 4; i++) {
int index = r.nextInt(codes.length());
String c = "" + codes.charAt(index);
float x = i * 1.0F * 70 / 4;
Font f = new Font("黑体", 3, 24);
g.setFont(f);
g.setColor(new Color(r.nextInt(200), r.nextInt(200), r.nextInt(200)));
g.drawString(c, (int) x, 30);
code += c;
}
// 画干扰线
for (int i = 0; i < 6; i++) {
int x1 = r.nextInt(70);
int y1 = r.nextInt(30);
int x2 = r.nextInt(70);
int y2 = r.nextInt(30);
g.setColor(Color.BLUE);
g.drawLine(x1, y1, x2, y2);
}
req.getSession(true).setAttribute("code", code);//将随机的验证码储存在session中,以用来之后用户输入验证码后进行比对
ImageIO.write(buffer, "jpg", resp.getOutputStream());//通过流的形式输出
}