java如何获取HttpServletRequest
时间: 2023-10-14 15:09:40 浏览: 79
Java service层获取HttpServletRequest工具类的方法
5星 · 资源好评率100%
在Java中,可以通过以下方式获取HttpServletRequest:
1. 在Servlet中,可以直接从doGet()或doPost()方法的参数中获取HttpServletRequest对象,代码如下:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取HttpServletRequest对象
HttpServletRequest httpRequest = request;
}
```
2. 在JSP页面中,可以通过pageContext对象获取HttpServletRequest对象,代码如下:
```java
<%
// 获取HttpServletRequest对象
HttpServletRequest httpRequest = (HttpServletRequest) pageContext.getRequest();
%>
```
3. 在普通Java类中,可以通过ThreadLocal来获取HttpServletRequest对象,代码如下:
```java
public class RequestHolder {
private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<>();
public static void set(HttpServletRequest request) {
requestHolder.set(request);
}
public static HttpServletRequest get() {
return requestHolder.get();
}
public static void remove() {
requestHolder.remove();
}
}
```
在Servlet的doFilter()方法中,可以将HttpServletRequest对象存放到ThreadLocal中,然后在普通Java类中通过ThreadLocal获取HttpServletRequest对象,代码如下:
```java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
RequestHolder.set(httpRequest);
chain.doFilter(request, response);
RequestHolder.remove();
}
```
阅读全文