修改Controller From Filter中的@RequestBody对象

发布于 2024-10-24 19:42:18 字数 1268 浏览 1 评论 0原文

我想修改一个已经用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

厌倦 2024-10-31 19:42:18

与 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文