一、HttpServletResponse
HttpServletResponse
表示一个HTTP
响应
Servlet
中的 doXXX
方法的目的就是根据请求计算得到相应, 然后把响应的数据设置到 HttpServletResponse
对象中
然后 Tomcat
就会把这个 HttpServletResponse
对象按照 HTTP
协议的格式, 转成一个字符串, 并通过 Socket
写回给浏览器
1.1 HttpServletResponse核心方法
1.2 方法演示
@WebServlet("/status")
public class StatusServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(404);
resp.setContentType("text/heml;charset=utf-8");
resp.getWriter().write("返回404");
}
}
使用Fiddler抓包得到的响应:
HTTP/1.1 404
Content-Type: text/heml;charset=utf-8
Content-Length: 9
Date: Wed, 15 Nov 2023 06:36:28 GMT
返回404
1.3 通过header实现自动刷新
给HTTP
响应中设置Refresh:
时间
@WebServlet("/refresh")
public class RefreshServlet extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 每隔 1s 自动刷新一次.
resp.setHeader("Refresh", "1");
resp.getWriter().write("time=" + System.currentTimeMillis());
}
}
响应:
HTTP/1.1 200
Refresh: 1
Content-Length: 18
Date: Wed, 15 Nov 2023 06:46:09 GMT
time=1700030769011
1.4 通过header实现自动重定向
@WebServlet("/redirect")
public class RedirectServlet extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 用户访问这个路径的时候, 自动重定向到 搜狗主页 .
resp.sendRedirect("https://www.sogou.com");
}
}
HTTP/1.1 302
Location: https://www.sogou.com
Content-Length: 0
Date: Wed, 15 Nov 2023 06:54:19 GMT