Mike Flynn
Mike Flynn

Reputation: 24325

Modify @RequestBody object in Controller From Filter

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>

Upvotes: 3

Views: 2552

Answers (1)

gkamal
gkamal

Reputation: 21000

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.

Upvotes: 1

Related Questions