I am overriding preHandle() method of Spring boot HandlerInterceptor. When I am invoking getParameter() method on HttpServletRequest request it is returning null.

@Component
@Slf4J
public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        log.info("age::{}",request.getParameter("age"));

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}

controller class...

@RestController
@Slf4J
public class Controller {

    @PostMapping("/test")
    public void test(@RequestBody Person person){
        log.info("in test method");
    }
}

dto...

@Data
public class Person {
   private Integer age;
}

json body....

{"age":"34"}

output:

age:: null

Body is present in HttpServletRequest. i have verified it with bufferReader and getContentLength() but not able to access it via getParameter().

I have gone through below stack overflow links

https://stackoverflow.com/questions/1528628/logging-payload-of-posts-to-tomcat

https://stackoverflow.com/questions/15938780/httpservletrequest-getparameter-returns-null

http://natch3z.blogspot.com/2009/01/read-request-body-in-filter.html

These all helps to extract the data from request body but it requires a lot of custom code to be written. Is there any solution provided by spring using which directly I can access the param values.

Why getParameter() is returning null and how can we access the data directly?

Comment From: deepakThedeveloper

I have solved this problem in other way.

I have used IOUtils of apache, org.apache.commons.io.IOUtils

String data = IOUtils.toString(request.getReader());
Person person = new ObjectMapper().readValue(data, Person.class);

this solves my problem but still I feel it to be workaround as getParameter() should return appropriate value for key I think so.

Comment From: wilkinsona

getParameter provides access to request parameters. As noted in the method's javadoc, parameters are contained in the query string or come from posted form data. There's no query string involved here and you appear to be sending JSON which isn't posted form data so there are no parameters.

Without knowing exactly why you want to intercept the request and deserialise its json body, it's difficult to offer any further advice. This also isn't the right place to do so as we prefer to use the issue tracker for bugs and enhancements.

If you have any further questions, please follow up on Stack Overflow or Gitter. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.

Comment From: deepakThedeveloper

Thanks @wilkinsona . Will close this question here and take it further on stack over flow.