强制刷新 :除了禁止缓存以为,还需要给服务端传递一个唯一的参数值(没有实际用处)。随机数、时间
生成代码
<%@ page import="java.awt.*" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page contentType="image/jpeg;charset=UTF-8" language="java" %>
<%!
//随机产生颜色值
public Color getColor(){
Random ran=new Random();
int r = ran.nextInt(256);
int g = ran.nextInt(256);
int p = ran.nextInt(256);
return new Color(r,g,p);//red green blue三原色0-255
}
//产生验证码值
public String getNum(){
//0-8999 1000-9999
int ran=(int)(Math.random()*9000)+1000;
return String.valueOf(ran);
}
%>
<%
//禁止缓存,防止 验证码过期
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-control","no-cache");
response.setHeader("Expires","0");
//绘制验证码
BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
//画笔
Graphics graphics = image.getGraphics();
graphics.fillRect(0,0,80,30);
//绘制干扰线条
for(int i=0;i<60;i++){
Random random=new Random();
int xBegin = random.nextInt(80);
int yBegin = random.nextInt(30);
int xEnd= random.nextInt(xBegin+10);
int yEnd= random.nextInt(yBegin+10);
graphics.setColor(getColor());
//绘制线条
graphics.drawLine(xBegin,yBegin,xEnd,yEnd);
}
graphics.setFont(new Font("seif",Font.BOLD,20));
//绘制验证码
graphics.setColor(Color.BLACK);
String checkCode=getNum();
StringBuffer sb=new StringBuffer();
for(int i=0;i<checkCode.length();i++){
sb.append(checkCode.charAt(i));//验证码的每一位数字
}
graphics.drawString(sb.toString(),15,20);//绘制验证码
//将验证码真实值保存zaisession中
session.setAttribute("checkCode",checkCode);
//真实的产生图片
ImageIO.write(image,"jpeg",response.getOutputStream());
//关闭
out.clear();
out=pageContext.pushBody();//<input type="image" src="xxx">
%>