设置某些页面缓存或是不缓存
要想让所有浏览器不缓存页面:
<%
response.setHeader("expires","-1");
response.setHeader("pragma","no-cache");
response.setHeader("cache-control","no-cache");
%>
分析:通过一个过虑器,对所有*.jsp过虑,设置三个头,全部不缓存。
第一步:实现过虑器接口
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//转换
HttpServletResponse resp = (HttpServletResponse) response;
resp.setHeader("expires","-1");
resp.setHeader("pragma","no-cache");
resp.setHeader("cache-control","no-cache");
//都放行
chain.doFilter(request, response);
}
第二步:配置过虑器,url-pattern=*.jsp
<!-- 配置控制缓存的filter -->
<filter>
<filter-name>cache</filter-name>
<filter-class>cn.itcast.filter.CacheFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cache</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
第三步:设置对某些页面缓存N天
HttpServletResponse resp = (HttpServletResponse) response;
//计算2天以后的毫秒值
//日历
Calendar cl = Calendar.getInstance();
//日历上加2天
long time = cl.getTimeInMillis();
resp.setDateHeader("expires", time);[W2]
//resp.setHeader("expires",""+time);
// resp.setHeader("pragma","no-cache");
// resp.setHeader("cache-control","no-cache");
//都放行
chain.doFilter(request,resp);
生成验证码:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置响应类型
resp.setContentType("image/jpeg");
int width=60;
int height=30;
BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0, width, height);
g.setFont(new Font("宋体", Font.BOLD,18));
Random r = new Random();
for(int i=0;i<4;i++){
Color c = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
int code = r.nextInt(10);
g.setColor(c);
g.drawString(""+code,i*15,10+r.nextInt(20));
}
for(int i=0;i<10;i++){
Color c = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
g.setColor(c);
g.drawLine(r.nextInt(60),r.nextInt(30),r.nextInt(60),r.nextInt(30));
}
//图片生效
g.dispose();
//写到
ImageIO.write(img, "JPEG",resp.getOutputStream());
}