-1

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

Logging Payload of POSTs to Tomcat

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
anonymous
  • 47
  • 10

1 Answers1

0

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.

anonymous
  • 47
  • 10