【JavaEE】Servlet API 详解(HttpServletResponse类方法演示、实现自动刷新、实现自动重定向)

一、HttpServletResponse

HttpServletResponse表示一个HTTP响应

Servlet 中的 doXXX 方法的目的就是根据请求计算得到相应, 然后把响应的数据设置到 HttpServletResponse 对象中

然后 Tomcat 就会把这个 HttpServletResponse 对象按照 HTTP 协议的格式, 转成一个字符串, 并通过 Socket 写回给浏览器

1.1 HttpServletResponse核心方法

1.2 方法演示

java 复制代码
@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抓包得到的响应:

xml 复制代码
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:时间

java 复制代码
@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());
    }
}

响应:

xml 复制代码
HTTP/1.1 200
Refresh: 1
Content-Length: 18
Date: Wed, 15 Nov 2023 06:46:09 GMT

time=1700030769011

1.4 通过header实现自动重定向

java 复制代码
@WebServlet("/redirect")
public class RedirectServlet extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 用户访问这个路径的时候, 自动重定向到 搜狗主页 .
        resp.sendRedirect("https://www.sogou.com");
    }
}
xml 复制代码
HTTP/1.1 302
Location: https://www.sogou.com
Content-Length: 0
Date: Wed, 15 Nov 2023 06:54:19 GMT
相关推荐
老马识途2.04 小时前
java处理接口返回的json数据步骤 包括重试处理,异常抛出,日志打印,注意事项
java·开发语言
2***d8854 小时前
Spring Boot中的404错误:原因、影响及处理策略
java·spring boot·后端
c***69304 小时前
Springboot项目:使用MockMvc测试get和post接口(含单个和多个请求参数场景)
java·spring boot·后端
6***A6634 小时前
Springboot中SLF4J详解
java·spring boot·后端
五阿哥永琪4 小时前
Hutool中常用的工具类&真实项目的黄金组合
java
xun-ming4 小时前
Redis实战之7种数据结构
java
5***84644 小时前
Spring Boot的项目结构
java·spring boot·后端
SimonKing4 小时前
基于Netty的TCP协议的Socket客户端
java·后端·程序员
程序员飞哥4 小时前
几年没面试,这次真的被打醒了!
java·面试
Learner4 小时前
Python异常处理
java·前端·python