3

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>
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341
  • Where is the filter being instantiated? When you say you can't get the attributes, do you mean on the client side? – Justin Thomas Mar 23 '11 at 05:07
  • I want to modify @RequestBody FollowRequest request inside the Request Filter, before it goes to the Controller so I can have the IP and Referrer in that object. The filter is instantiated in the web.xml which I added above. – Mike Flynn Mar 23 '11 at 15:57
  • You can modify the request body, see here: https://stackoverflow.com/questions/50932518/how-to-modify-request-body-before-reaching-controller-in-spring-boot – hieinji Oct 23 '19 at 16:54

1 Answers1

1

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.

gkamal
  • 20,777
  • 4
  • 60
  • 57