【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
相关推荐
5980354152 分钟前
【java工具类】小数、整数转中文大写
android·java·开发语言
JIngJaneIL9 分钟前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
吃喝不愁霸王餐APP开发者20 分钟前
Java后端服务在对接全国性霸王餐API时的多数据中心部署与就近调用策略
java·开发语言
从心归零28 分钟前
springboot-jpa的批量更新方法
java·spring boot·spring
这周也會开心37 分钟前
128陷阱,==与equals区别
java·开发语言
TAEHENGV1 小时前
回收站模块 Cordova 与 OpenHarmony 混合开发实战
android·java·harmonyos
a努力。2 小时前
宇树Java面试被问:方法区、元空间的区别和演进
java·后端·面试·宇树科技
2501_916766542 小时前
【面试题1】128陷阱、==和equals的区别
java·开发语言
a程序小傲3 小时前
蚂蚁Java面试被问:注解的工作原理及如何自定义注解
java·开发语言·python·面试
幽络源小助理3 小时前
SpringBoot+Vue摄影师分享社区源码 – Java项目免费下载 | 幽络源
java·vue.js·spring boot