在Java Web开发中,HttpServletRequest
和HttpServletResponse
是用于处理客户端请求和服务器响应的两个关键接口。它们提供了丰富的方法来处理和操控HTTP请求和响应。以下是这些接口的一些常见操作和示例。
HttpServletRequest
常见操作
获取请求参数
- 单个参数:
String paramValue = request.getParameter("paramName");
- 多个参数:
String[] paramValues = request.getParameterValues("paramName");
获取请求头信息
- 单个请求头:
String headerValue = request.getHeader("headerName");
- 所有请求头:
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
// Process header
}
获取请求方法
String method = request.getMethod(); // GET, POST
获取请求URL和URI
String requestURI = request.getRequestURI();
StringBuffer requestURL = request.getRequestURL();
获取客户端IP地址
String clientIP = request.getRemoteAddr();
获取请求上下文路径
String contextPath = request.getContextPath();
获取Session对象
HttpSession session = request.getSession();
读取请求体数据(例如,处理POST请求的数据)
BufferedReader reader = request.getReader();
StringBuilder body = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
body.append(line);
}
// body.toString() contains the request body
HttpServletResponse
常见操作
设置响应状态码
response.setStatus(HttpServletResponse.SC_OK); // 200
response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404
设置响应头
response.setHeader("Content-Type", "text/html");
response.setHeader("Cache-Control", "no-cache");
设置响应内容类型
response.setContentType("text/html;charset=UTF-8");
设置响应体内容
PrintWriter out = response.getWriter();
out.println("<html><body>Hello, World!</body></html>");
out.flush();
重定向
response.sendRedirect("http://www.example.com");
发送错误响应
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
示例代码
以下是一个综合示例,展示了如何在Servlet中使用HttpServletRequest
和HttpServletResponse
:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取请求参数
String param = request.getParameter("param");
// 设置响应内容类型
response.setContentType("text/html;charset=UTF-8");
// 设置响应头
response.setHeader("Custom-Header", "value");
// 获取响应输出流
PrintWriter out = response.getWriter();
// 写入响应内容
out.println("<html>");
out.println("<head><title>Example</title></head>");
out.println("<body>");
out.println("<h1>Parameter: " + param + "</h1>");
out.println("</body>");
out.println("</html>");
out.flush();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 读取请求体数据
BufferedReader reader = request.getReader();
StringBuilder body = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
body.append(line);
}
// 打印请求体
System.out.println("Request Body: " + body.toString());
// 设置响应状态码
response.setStatus(HttpServletResponse.SC_OK);
// 设置响应内容类型
response.setContentType("application/json;charset=UTF-8");
// 写入响应内容
PrintWriter out = response.getWriter();
out.println("{\"message\": \"Data received\"}");
out.flush();
}
}