生成图片的servlet路径是/imagepublic class ImageServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置响应的类型
response.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, width);//填充背景矩形
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));
g.setColor(c);//设置颜色
g.drawString(""+r.nextInt(10),i*15, 10+r.nextInt(10));
}
//绘制干扰线
for(int i=0;i<7;i++){
//获取随机色
Color c = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
g.setColor(c);//设置颜色
g.drawLine(r.nextInt(width),r.nextInt(height) ,r.nextInt(width),r.nextInt(height));
}
//图片生效
g.dispose();
//输出图片
ImageIO.write(img, "JPEG", response.getOutputStream());
}
}
用过滤器使对/image的访问内容不缓存
public class CacheFilter implements Filter{ public void destroy() {
} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
                //设置响应头让浏览器不缓存数据
res.setHeader("expires","-1");
res.setHeader("pragma","no-cache");
res.setHeader("cache-control","no-cache");
System.out.println("执行CacheFilter...");
chain.doFilter(request, response);
} public void init(FilterConfig filterConfig) throws ServletException {
}}
index.jsp访问页面<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="
text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
   <img id="img" src="<c:url value='/image'/>"/>  <a href="javascript:_chg();">看不清</a>
  </body>
  <script type="text/javascript">
   function _chg(){
   var img = document.getElementById("img");
   img.src = "<c:url value='/image'/>";
                //用js更换img的src路径没用
                   //ie下确实没有缓存该图片
   alert(img.src);
   }
  </script>
</html>
 上面代码在ie和firefox下均不能实现更换验证码但在360和谷歌浏览器下有用验证码浏览器缓存图片filter