【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
相关推荐
FrankYoou1 小时前
Jenkins 与 GitLab CI/CD 的核心对比
java·docker
麦兜*1 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了2 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
天河归来2 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
weixin_478689762 小时前
十大排序算法汇总
java·算法·排序算法
码荼2 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud
IT_10242 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
ye903 小时前
银河麒麟V10服务器版 + openGuass + JDK +Tomcat
java·开发语言·tomcat
武昌库里写JAVA3 小时前
Oracle如何使用序列 Oracle序列使用教程
java·开发语言·spring boot·学习·课程设计
做题不NG4 小时前
大模型应用开发-LangChain4j
java