Java Web核心类:HttpServletRequest和HttpServletResponse
核心关系图
首先,通过下图可以直观地理解这三者在处理一个 HTTP 请求时的角色和交互流程:
1. HttpServlet
javax.servlet.http.HttpServlet 是一个抽象类,你通过继承它来创建一个能够处理 HTTP 请求的 Servlet。
主要功能和工作原理:
-
请求路由:它的核心方法是
service(HttpServletRequest, HttpServletResponse)。该方法会根据请求的 HTTP 方法(GET, POST, PUT, DELETE 等)自动调用对应的doXXX方法。你不需要重写service方法,只需要重写你关心的doGet,doPost等方法即可。 -
生命周期管理:它提供了
init(),destroy()等方法,用于管理 Servlet 的生命周期(初始化、销毁)。
常用方法(需要重写):
-
doGet(HttpServletRequest req, HttpServletResponse resp)
处理 GET 请求。通常用于获取资源,如显示一个页面、查询数据。 -
doPost(HttpServletRequest req, HttpServletResponse resp)
处理 POST 请求。通常用于提交数据,如表单提交、文件上传。 -
doPut(HttpServletRequest req, HttpServletResponse resp)
处理 PUT 请求。通常用于更新整个资源。 -
doDelete(HttpServletRequest req, HttpServletResponse resp)
处理 DELETE 请求。通常用于删除资源。 -
init()和destroy()
用于初始化和清理资源。
示例代码:
java
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
// 使用注解配置 Servlet 的访问 URL
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 处理 GET 请求到 /hello
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 处理 POST 请求到 /hello
String name = request.getParameter("name");
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Hello, " + name + "!");
}
}
2. HttpServletRequest
javax.servlet.http.HttpServletRequest 接口的一个实例对象,代表了客户端的 HTTP 请求。Servlet 容器(如 Tomcat)会为每一个收到的请求创建一个 HttpServletRequest 对象,并将它传递给 Servlet 的 service 方法。
主要功能:
-
获取请求参数:最常用的功能,获取来自客户端的数据,如表单字段、URL 查询字符串。
-
获取请求头信息:如
User-Agent,Cookie,Referer等。 -
获取客户端信息:如客户端的 IP 地址、请求的 URL。
-
管理属性:可以在请求范围内存储和获取数据(通过
setAttribute和getAttribute),常用于在 Servlet 和 JSP 之间传递数据。
常用方法:
-
获取参数:
-
String getParameter(String name)
获取单个请求参数的值。 -
String[] getParameterValues(String name)
获取多个值的请求参数(如复选框)。 -
Map getParameterMap()
获取所有参数的 Map。
-
-
获取请求信息:
-
String getMethod()
获取 HTTP 方法(GET, POST)。 -
String getRequestURI()
获取请求的 URI。 -
String getRemoteAddr()
获取客户端的 IP 地址。
-
-
获取请求头:
-
String getHeader(String name)
获取指定名称的请求头。
-
-
管理属性:
-
void setAttribute(String name, Object obj) -
Object getAttribute(String name)
-
-
获取会话:
-
HttpSession getSession()
获取或创建与当前请求关联的 Session。
-
示例代码:
java
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1. 获取表单参数
String username = request.getParameter("username");
String password = request.getParameter("password");
String[] hobbies = request.getParameterValues("hobby"); // 假设是多选框
// 2. 获取客户端信息
String clientIP = request.getRemoteAddr();
String method = request.getMethod();
// 3. 将数据设置到请求属性中,以便转发给 JSP
request.setAttribute("user", username);
// ... 后续处理
}
3. HttpServletResponse
javax.servlet.http.HttpServletResponse 接口的一个实例对象,代表了服务器对客户端的 HTTP 响应。你可以通过这个对象来设置响应的所有信息。
主要功能:
-
设置响应状态码:如 200(成功)、404(未找到)、500(服务器错误)。
-
设置响应头:如设置内容类型(Content-Type)、缓存控制、Cookie。
-
获取输出流:向客户端发送响应体数据(HTML、JSON、文本等)。
常用方法:
-
设置状态码:
-
void setStatus(int sc)
设置状态码。 -
void sendError(int sc, String msg)
发送错误状态码和消息。
-
-
设置响应头:
-
void setContentType(String type)
非常重要:设置响应内容的 MIME 类型,如"text/html","application/json"。通常也会在这里设置字符编码,例如"text/html;charset=UTF-8"。 -
void setCharacterEncoding(String charset)
设置响应体的字符编码。 -
void addCookie(Cookie cookie)
向客户端添加一个 Cookie。 -
void sendRedirect(String location)
发送重定向指令(状态码 302)。
-
-
获取输出流:
-
PrintWriter getWriter()
获取字符输出流,用于输出文本内容(HTML, JSON)。 -
ServletOutputStream getOutputStream()
获取字节输出流,用于输出二进制内容(图片、文件)。
-
示例代码:
java
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse responsewww.ylzx.gov.cn/show.php?cid=43&id=600020
www.ylzx.gov.cn/show.php?cid=43&id=600021
www.ylzx.gov.cn/show.php?cid=43&id=600022
www.ylzx.gov.cn/show.php?cid=43&id=600023
www.ylzx.gov.cn/show.php?cid=43&id=600024
www.ylzx.gov.cn/show.php?cid=43&id=600025
www.ylzx.gov.cn/show.php?cid=43&id=600026
www.ylzx.gov.cn/show.php?cid=43&id=600027
www.ylzx.gov.cn/show.php?cid=43&id=600028
www.ylzx.gov.cn/show.php?cid=43&id=600029
www.ylzx.gov.cn/show.php?cid=43&id=600030
www.ylzx.gov.cn/show.php?cid=43&id=600031
www.ylzx.gov.cn/show.php?cid=43&id=600032
www.ylzx.gov.cn/show.php?cid=43&id=600033
www.ylzx.gov.cn/show.php?cid=43&id=600034
www.ylzx.gov.cn/show.php?cid=43&id=600035
www.ylzx.gov.cn/show.php?cid=43&id=600036
www.ylzx.gov.cn/show.php?cid=43&id=600037
www.ylzx.gov.cn/show.php?cid=43&id=600038
www.ylzx.gov.cn/show.php?cid=43&id=600039) throws IOException {
// 1. 设置响应类型和编码
response.setContentType("text/html;charset=UTF-8");
// 2. 获取字符输出流
PrintWriter out = response.getWriter();
// 3. 构建 HTML 内容并输出
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head><title>My Page</title></head>");
out.println("<body>");
out.println(" <h1>数据提交成功!</h1>");
out.println("</body>");
out.println("</html>");
}
// 返回 JSON 数据的例子
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 设置响应类型为 JSON
response.setContentType("application/json;charset=UTF-8"www.ylzx.gov.cn/show.php?cid=43&id=600000
www.ylzx.gov.cn/show.php?cid=43&id=600001
www.ylzx.gov.cn/show.php?cid=43&id=600002
www.ylzx.gov.cn/show.php?cid=43&id=600003
www.ylzx.gov.cn/show.php?cid=43&id=600004
www.ylzx.gov.cn/show.php?cid=43&id=600005
www.ylzx.gov.cn/show.php?cid=43&id=600006
www.ylzx.gov.cn/show.php?cid=43&id=600007
www.ylzx.gov.cn/show.php?cid=43&id=600008
www.ylzx.gov.cn/show.php?cid=43&id=600009
www.ylzx.gov.cn/show.php?cid=43&id=600010
www.ylzx.gov.cn/show.php?cid=43&id=600011
www.ylzx.gov.cn/show.php?cid=43&id=600012
www.ylzx.gov.cn/show.php?cid=43&id=600013
www.ylzx.gov.cn/show.php?cid=43&id=600014
www.ylzx.gov.cn/show.php?cid=43&id=600015
www.ylzx.gov.cn/show.php?cid=43&id=600016
www.ylzx.gov.cn/show.php?cid=43&id=600017
www.ylzx.gov.cn/show.php?cid=43&id=600018
www.ylzx.gov.cn/show.php?cid=43&id=600019);
String jsonResponse = "{\"status\": \"success\", \"message\": \"Hello JSON\"}";
PrintWriter out = response.getWriter();
out.print(jsonResponse);
out.flush();
}
// 重定向的例子
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 处理完 POST 请求后,重定向到另一个页面(防止重复提交)
response.sendRedirect("/success.jsp");
}
总结
| 类/接口 | 角色 | 核心职责 |
|---|---|---|
HttpServlet |
请求处理器 | 继承它来创建 Servlet,重写 doGet/doPost 等方法以定义业务逻辑。 |
HttpServletRequest |
请求的抽象 | 从中获取所有来自客户端的信息:参数、头、URL、Session 等。 |
HttpServletResponse |
响应的抽象 | 通过它构建返回给客户端的一切:状态、头、内容(HTML/JSON)。 |
简单流程:
-
用户发起一个 HTTP 请求(例如,提交一个表单)。
-
服务器(如 Tomcat)接收到请求,创建
HttpServletRequest和HttpServletResponse对象。 -
服务器调用对应的
HttpServlet的service方法。 -
service方法根据请求方法(GET/POST)路由到你的doGet或doPost方法。 -
在你的
doXXX方法中:-
从
HttpServletRequest对象中读取信息。 -
执行你的业务逻辑。
-
通过
HttpServletResponse对象返回响应。
-
-
服务器将构建好的 HTTP 响应发送回客户端。
更多推荐

所有评论(0)