【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
相关推荐
wuminyu3 小时前
JVM规范学习总结:解释器与JIT编译器如何处理JVM字节码
java·linux·c语言·jvm·c++
txxzjmzlh3 小时前
SpringBoot 配置⽂件
java·spring boot·spring
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 搜索附近的功能概述和分析
java·开发语言·交友
骑着蜗牛撵大象3274 小时前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
独泪了无痕4 小时前
Hutool之LocalDateTimeUtil:让时间间隔操作如虎添翼
java
三无少女指南5 小时前
从这里开始:Java 后端与 AI 工程的三条阅读路线
java·学习路线·ai工程
香蕉大香蕉(06敬畏市场)5 小时前
MySQL 单点详解(07)
java·数据库·mysql·ai·博客·八股
nice_lcj5206 小时前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
骑着蜗牛撵大象3276 小时前
2026 后端 AI 工程化:Spring AI 管调用、MCP 管工具、Agent 内嵌管自治
java·人工智能·后端·spring·ai·可观测性·mcp
tryxr6 小时前
JVM 垃圾回收机制
java·jvm·gc·垃圾回收