如何使用攔截器獲取請求的入?yún)⒉⑵滢D(zhuǎn)化為Java對象詳解
在SpringBoot中實(shí)現(xiàn)一個(gè)攔截器(HandlerInterceptor),用于獲取請求的入?yún)⒉⑵滢D(zhuǎn)化為 Java 對象。
方式一:攔截器配合過濾器
1. 設(shè)計(jì)思路
在 Web 開發(fā)中,當(dāng) HTTP 請求發(fā)送到服務(wù)器時(shí),Spring 會(huì)通過一個(gè)鏈條處理這個(gè)請求,這個(gè)鏈條包括很多組件,比如:攔截器(HandlerInterceptor)、過濾器(Filter)、控制器(Controller)、參數(shù)解析器(比如 Spring MVC 的 @RequestParam 或 @RequestBody 等注解)等。
輸入流的問題
當(dāng)客戶端通過 POST 請求發(fā)送數(shù)據(jù)時(shí),數(shù)據(jù)通常是包含在請求體中的(比如表單數(shù)據(jù)或者 JSON 數(shù)據(jù))。Spring 的 HttpServletRequest 提供了 getInputStream() 方法來讀取請求體中的數(shù)據(jù)。
問題: HttpServletRequest.getInputStream() 只能讀取一次。也就是說,當(dāng)你在攔截器中調(diào)用了 getInputStream() 讀取數(shù)據(jù)時(shí),流就被消費(fèi)掉了,后續(xù)的組件(例如,Spring 的參數(shù)解析器)再調(diào)用 getInputStream() 就無法讀取到數(shù)據(jù)了,因?yàn)榱饕呀?jīng)被關(guān)閉了。
解決方案
解決這個(gè)問題的思路是:在攔截器中讀取請求體的數(shù)據(jù)時(shí),不直接從 HttpServletRequest 中讀取,而是通過包裝(HttpServletRequestWrapper)的方式,重新實(shí)現(xiàn) getInputStream(),將讀取的數(shù)據(jù)緩存下來,確保后續(xù)的處理鏈依然能夠訪問到請求體的內(nèi)容。
2. 如何實(shí)現(xiàn)
- 創(chuàng)建一個(gè)
HttpServletRequestWrapper類:它將重寫getInputStream()方法,讓流的數(shù)據(jù)可以多次讀取。通過這個(gè)類緩存請求體的內(nèi)容。 - 創(chuàng)建一個(gè)
Filter:用于包裝請求,將HttpServletRequest包裝成我們自己的HttpServletRequestWrapper。 - 在攔截器中獲取請求體:在
HandlerInterceptor中獲取請求體并進(jìn)行解析。
3. 實(shí)現(xiàn)步驟
3.1 創(chuàng)建 HttpServletRequestWrapper
這個(gè)類主要作用是緩存請求體內(nèi)容,并且重寫 getInputStream(),讓它能夠多次讀取。
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class CachedBodyHttpServletRequestWrapper extends HttpServletRequestWrapper {
private byte[] requestBody;
public CachedBodyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
// 從 InputStream 讀取數(shù)據(jù),緩存請求體內(nèi)容
InputStream inputStream = request.getInputStream();
this.requestBody = inputStream.readAllBytes(); // 將流中的數(shù)據(jù)讀取到字節(jié)數(shù)組中
}
@Override
public InputStream getInputStream() throws IOException {
// 返回緩存的數(shù)據(jù)
return new ByteArrayInputStream(requestBody);
}
public byte[] getRequestBody() {
return requestBody;
}
}
3.2 創(chuàng)建 Filter 以包裝 HttpServletRequest
這個(gè)過濾器的作用是將原始的 HttpServletRequest 替換為我們自定義的 CachedBodyHttpServletRequestWrapper。
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter("/*") // 這個(gè)過濾器會(huì)攔截所有請求
public class RequestWrapperFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化操作
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 僅對 HttpServletRequest 進(jìn)行包裝
if (request instanceof HttpServletRequest) {
CachedBodyHttpServletRequestWrapper wrappedRequest =
new CachedBodyHttpServletRequestWrapper((HttpServletRequest) request);
// 將包裝后的請求傳遞給下一個(gè)過濾器
chain.doFilter(wrappedRequest, response);
} else {
// 對非 HttpServletRequest 請求不做任何處理
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
// 銷毀操作
}
}
3.3 創(chuàng)建攔截器 HandlerInterceptor 以處理請求參數(shù)
接下來,在 Spring 的攔截器中獲取請求體并解析成 Java 對象。這個(gè)攔截器將會(huì)在請求進(jìn)入控制器之前進(jìn)行攔截。
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RequestBodyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws IOException {
if (request instanceof CachedBodyHttpServletRequestWrapper) {
// 獲取包裝后的請求體
CachedBodyHttpServletRequestWrapper wrappedRequest = (CachedBodyHttpServletRequestWrapper) request;
String requestBody = new String(wrappedRequest.getRequestBody(), "UTF-8");
// 打印或處理請求體內(nèi)容
System.out.println("Request Body: " + requestBody);
// 將請求體轉(zhuǎn)換成 Java 對象
MyRequestObject myRequestObject = new ObjectMapper().readValue(requestBody, MyRequestObject.class);
System.out.println("Parsed Java Object: " + myRequestObject);
}
return true; // 返回 true,表示繼續(xù)處理請求
}
}
3.4 注冊攔截器和過濾器
- 在 Spring Boot 中注冊
Filter:
提示 :在Spring Boot項(xiàng)目中,Filter會(huì)自動(dòng)注冊到應(yīng)用上下文中,可以不手動(dòng)注冊。
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<RequestWrapperFilter> loggingFilter() {
FilterRegistrationBean<RequestWrapperFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new RequestWrapperFilter());
registrationBean.addUrlPatterns("/api/*"); // 這里根據(jù)需要配置攔截的 URL
return registrationBean;
}
}
- 在 Spring Boot 中注冊
HandlerInterceptor:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private RequestBodyInterceptor requestBodyInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestBodyInterceptor).addPathPatterns("/api/*"); // 根據(jù)需要配置路徑
}
}
4. 總結(jié)
通過以上步驟,你可以實(shí)現(xiàn)一個(gè)能夠多次讀取 HttpServletRequest.getInputStream() 數(shù)據(jù)的機(jī)制。基本思路是:
- 創(chuàng)建一個(gè)
HttpServletRequestWrapper類來緩存請求體內(nèi)容; - 通過
Filter來包裝HttpServletRequest; - 在
HandlerInterceptor中獲取請求體并進(jìn)行處理。
這樣,無論在攔截器還是后續(xù)的參數(shù)解析過程中,都會(huì)能夠多次訪問請求體數(shù)據(jù)。
方式二:攔截器中使用包裝類ContentCachingRequestWrapper
在 HTTP 請求中,HttpServletRequest 的請求體(POST 請求中的 JSON 數(shù)據(jù))是一次性的流,讀取完一次之后,如果沒有特殊處理,就不能再次讀取它。
ContentCachingRequestWrapper 是 Spring 框架提供的一個(gè)包裝類,它的作用是“包裝”原始的 HttpServletRequest 對象,使得請求體內(nèi)容可以被多次讀取。
使用ContentCachingRequestWrapper ,省去方法一中創(chuàng)建的 HttpServletRequestWrapper和RequestWrapperFilter。
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RequestBodyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws IOException {
if (HttpMethod.POST.matches(request.getMethod())) {
// 包裝請求,使其可以多次讀取請求體
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
// 讀取請求體,明確指定字符編碼為 UTF-8
String requestBody = new String(wrappedRequest.getContentAsByteArray(), "UTF-8");
// 打印或處理請求體內(nèi)容
System.out.println("Request Body: " + requestBody);
// 將請求體轉(zhuǎn)換成 Java 對象
MyRequestObject myRequestObject = new ObjectMapper().readValue(requestBody, MyRequestObject.class);
System.out.println("Parsed Java Object: " + myRequestObject);
}
return true; // 返回 true,表示繼續(xù)處理請求
}
}
總結(jié)
ContentCachingRequestWrapper 是一種非常有用的工具,允許緩存并多次讀取請求體內(nèi)容,尤其需要在攔截器中處理請求體數(shù)據(jù)時(shí),它非常有效。
到此這篇關(guān)于如何使用攔截器獲取請求的入?yún)⒉⑵滢D(zhuǎn)化為Java對象的文章就介紹到這了,更多相關(guān)攔截器獲取請求入?yún)⒉⑥D(zhuǎn)化Java對象內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot+Vue實(shí)現(xiàn)EasyPOI導(dǎo)入導(dǎo)出的方法詳解
項(xiàng)目開發(fā)過程中,很大的需求都有 導(dǎo)入導(dǎo)出功能。本文將利用SpringBoot+Vue實(shí)現(xiàn)EasyPOI導(dǎo)入導(dǎo)出功能,感興趣的可以了解一下2022-08-08
Java關(guān)鍵字synchronized原理與鎖的狀態(tài)詳解
在Java當(dāng)中synchronized關(guān)鍵字通常是用來標(biāo)記一個(gè)方法或者代碼塊。本文將通過示例為大家詳細(xì)介紹一下Synchronized的各種使用方法,需要的可以參考一下2022-08-08
SpringBoot文件上傳控制及Java 獲取和判斷文件頭信息
這篇文章主要介紹了SpringBoot文件上傳控制的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-12-12
Java實(shí)戰(zhàn)項(xiàng)目之斗地主和斗牛游戲的實(shí)現(xiàn)
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Java實(shí)現(xiàn)一個(gè)斗地主和一個(gè)斗牛游戲,大家可以在過程中查缺補(bǔ)漏,提升水平2021-11-11
SpringBoot兩種方式接入DeepSeek的實(shí)現(xiàn)
本文主要介紹了SpringBoot兩種方式接入DeepSeek的實(shí)現(xiàn),包括HttpClient方式和基于spring-ai-openai的方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03

