我有一个 spring boot 应用程序。 我更改每个发布请求的请求正文。 是否可以在请求到达 Controller 之前修改请求主体。 请包括一个例子。
最佳答案
另一种方法是向 HttpServletRequest 对象添加一个属性。之后,您可以使用 @RequestAttribute 注释在 Controller 类中读取该属性。
在拦截器中
@Component
public class SimpleInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException, IOException {
String parameter = request.getParameter("parameter");
if (parameter == "somevalue") {
request.setAttribute("customAttribute", "value");
}
return true;
}
}
在 Controller 中
@RestController
@RequestMapping("")
public class SampleController {
@RequestMapping(value = "/sample",method = RequestMethod.POST)
public String work(@RequestBody SampleRequest sampleRequest, @RequestAttribute("customAttribute") String customAttribute) {
System.out.println(customAttribute);
return "This works";
}
}
这具有不修改请求正文的优点。
关于java - 如何在 spring boot 到达 Controller 之前修改请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932518/