如何在到达spring控制器之前修改请求体中发送的JSON对象?
我尝试添加过滤器,但是一旦从请求中读取(servletrequest.getReader())然后将请求转发到过滤器链中的下一个过滤器,它就会失败(请求不会到达控制器)。
BufferedReader reader = servletrequest.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
String data = buffer.toString();
使用这个我在字符串中得到了JSON,但是我无法弄清楚如何将它放回请求中。
答案 0 :(得分:1)
使用Spring的HandlerInterceptor。您还可以专门选择拦截特定请求。检查this tutorial。这完全取决于您使用的Spring版本。但是这应该会让您对如何实现它有一个公平的展望。
package com.test.intercept;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class HttpRequestInterceptor extends HandlerInterceptorAdapter {
@Autowired
private ServletContext context;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
String methodName = handlerMethod.getMethod().getName();
Map<String, String> headerMap = HttpUtil.getAllHeaders(request);
Boolean isAllowed=false;
//doing what you want to your json
//
return isAllowed;
}
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
logger.info("in after completion");
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
logger.info("in posthandle");
}
并在您的servletContext.xml中添加:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/api/**" /> <!--to exclude a path -->
<mvc:exclude-mapping path="/web/**" /> <!--to exclude a path -->
<beans:bean class="com.test.interceptor.HttpRequestInterceptor"></beans:bean>
</mvc:interceptor>
</mvc:interceptors>