修改Controller From Filter中的@RequestBody对象
我想修改一个已经用 JacksonMapper 填充的对象,并自动向其添加 IP 和 Referrer URL,但请求始终为空,因为在属性数组中找不到它。我做错了什么吗?
ApiController.java
@RequestMapping(value="/member/follow")
public @ResponseBody IHttpResponse follow(@RequestBody FollowRequest request) {
return request.getHttpResponse();
}
ApiRequestWrapper.js
public class ApiRequestWrapper extends HttpServletRequestWrapper
{
public ApiRequestWrapper(HttpServletRequest request) {
super(request);
if(this.getAttribute("request") instanceof IHttpRequest)
{
IHttpRequest httpRequest = (IHttpRequest) this.getAttribute("request");
if(httpRequest != null)
{
httpRequest.setIp(request.getRemoteAddr());
httpRequest.setReferrer(request.getLocalName());
}
}
}
}
Web.xml
<filter>
<filter-name>apiFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>apiFilter</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>
I want to modify an object that has already been populated with JacksonMapper and add the IP and Referrer URL to it automatically, but the request is always null because it isn't found in the attributes array. Am I doing something wrong?
ApiController.java
@RequestMapping(value="/member/follow")
public @ResponseBody IHttpResponse follow(@RequestBody FollowRequest request) {
return request.getHttpResponse();
}
ApiRequestWrapper.js
public class ApiRequestWrapper extends HttpServletRequestWrapper
{
public ApiRequestWrapper(HttpServletRequest request) {
super(request);
if(this.getAttribute("request") instanceof IHttpRequest)
{
IHttpRequest httpRequest = (IHttpRequest) this.getAttribute("request");
if(httpRequest != null)
{
httpRequest.setIp(request.getRemoteAddr());
httpRequest.setReferrer(request.getLocalName());
}
}
}
}
Web.xml
<filter>
<filter-name>apiFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>apiFilter</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与 RequestBody 对应的对象是在调用该方法之前创建的 - 无法在过滤器中获取它。您可以通过实现一个方面来实现您想要做的事情。
The object corresponding to the RequestBody is created just before the method is invoked - there is no way to get hold of it in the filter. You can achieve what you want to do by implementing an Aspect.