首页 > 代码库 > Servlet请求头response应用简单案例
Servlet请求头response应用简单案例
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包:
Servlet请求头response应用简单案例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。