Servlet请求头response应用简单案例

时间:2023-12-10 15:06:26

Servlet请求头response应用简单案例:访问AServlet重定向到BServlet,5秒后跳到CServlet,并显示图片:

AServlet

 package cn.yzu;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("AServlet被访问到。。。。。。。。。");
//重定向请求头,可用一个response.sendRedirect("BServlet")代替;
response.setStatus(302);
response.setHeader("Location", "BServlet"); //取消缓存请求头,3个组合适用于所有浏览器,可用<meta>标签代替
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", -1);
}
}

BServlet

 package cn.yzu;

 import java.io.IOException;

 import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class BServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("BServlet被访问到。。。。。。。。。");
System.out.println("3秒钟后自动跳转到CServlet");
//自动刷新请求头
response.setHeader("Refresh", "3;URL=CServlet");
}
}

CServlet

 package cn.yzu;

 import java.io.FileInputStream;
import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; public class CServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("CServlet被访问到。。。。。。。。。");
//response响应字节流(万能的,也可以输出字符)
FileInputStream stream=new FileInputStream("C:/Users/Administrator/Desktop/UI/头像/Lebron.jpeg");
//IO小工具,Apache提供,将输入流转换成字节数组
byte bt[]=IOUtils.toByteArray(stream);
//注:绝对不可以和response.getWriter()同时使用,否则会抛IllegalStateException异常!!!!!!!
response.getOutputStream().write(bt); } }

运行结果:

Servlet请求头response应用简单案例

Servlet请求头response应用简单案例

注:IO小工具jar包:

Servlet请求头response应用简单案例