日期:2014-05-18 浏览次数:20961 次
<servlet> <servlet-name>PicChange</servlet-name> <servlet-class>PicChange</servlet-class> </servlet> <servlet-mapping> <servlet-name>PicChange</servlet-name> <url-pattern>/orz.jpg</url-pattern> </servlet-mapping>
import java.io.File; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class PicChange extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /*mir Mar 31, 2009*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); OutputStream out = response.getOutputStream(); //显示方式暂时采用传入的参数,可从数据库或者配置文件中获取定义 String orderOrRandom = (String)request.getParameter("random"); if(orderOrRandom==null||"".equals(orderOrRandom)){ orderOrRandom = "order"; }else if("true".equals(orderOrRandom)){ orderOrRandom = "random"; } String img = request.getSession().getServletContext().getRealPath("image"); File imgPath = new File(img); File[] imgList = imgPath.listFiles();//获得图片文件夹下的所有图片File Integer num; if("order".equals(orderOrRandom)){ HttpSession session = request.getSession(); num = (Integer)session.getAttribute("num"); if(num==null||num>=imgList.length){ num=0; } session.setAttribute("num", num+1); }else{ num = ((Double)(Math.random()*(imgList.length))).intValue(); } ImageIO.write(ImageIO.read(imgList[num]),"JPEG",out); } }