Servlet请求头response应用简单案例:访问AServlet重定向到BServlet,5秒后跳到CServlet,并显示图片:
AServlet
1 package cn.yzu; 2 import java.io.IOException; 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 public class AServlet extends HttpServlet { 8 9 public void doGet(HttpServletRequest request, HttpServletResponse response) 10 throws ServletException, IOException { 11 System.out.println("AServlet被访问到。。。。。。。。。"); 12 //重定向请求头,可用一个response.sendRedirect("BServlet")代替; 13 response.setStatus(302); 14 response.setHeader("Location", "BServlet"); 15 16 //取消缓存请求头,3个组合适用于所有浏览器,可用<meta>标签代替 17 response.setHeader("pragma", "no-cache"); 18 response.setHeader("cache-control", "no-cache"); 19 response.setDateHeader("expires", -1); 20 } 21 }
BServlet
1 package cn.yzu; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 public class BServlet extends HttpServlet { 11 public void doGet(HttpServletRequest request, HttpServletResponse response) 12 throws ServletException, IOException { 13 System.out.println("BServlet被访问到。。。。。。。。。"); 14 System.out.println("3秒钟后自动跳转到CServlet"); 15 //自动刷新请求头 16 response.setHeader("Refresh", "3;URL=CServlet"); 17 } 18 }
CServlet
1 package cn.yzu; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import org.apache.commons.io.IOUtils; 12 13 public class CServlet extends HttpServlet { 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 System.out.println("CServlet被访问到。。。。。。。。。"); 17 //response响应字节流(万能的,也可以输出字符) 18 FileInputStream stream=new FileInputStream("C:/Users/Administrator/Desktop/UI/头像/Lebron.jpeg"); 19 //IO小工具,Apache提供,将输入流转换成字节数组 20 byte bt[]=IOUtils.toByteArray(stream); 21 //注:绝对不可以和response.getWriter()同时使用,否则会抛IllegalStateException异常!!!!!!! 22 response.getOutputStream().write(bt); 23 24 } 25 26 }
运行结果:
注:IO小工具jar包:
时间: 2024-10-17 08:37:38