Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC custom message for HTTP 400

I have several SprigMVC methods like this below, returning either a ModelAndView or a Responsebody. When users makes a request to these urls missing the required parameters they naturally get the message "Required String parameter 'id' is not present".

From security perspective I want to hide this detailed description messages from users. So a hacker don't easily know the missing parameters and will get a 400 error without any description. Is this possible via a spring configuration/Spring Security or I have to manually refactor all my methods to return a custom message somehow.

@RequestMapping(value = "/payment", method = RequestMethod.GET)
public ModelAndView getReponse(@RequestParam(value = "id", required = true)) {

    return model;
}

@RequestMapping(value = "/status", method = RequestMethod.GET)
public @ResponseBody String getStatus(@RequestParam(value = "id", required = true) String id) {

    return "string";
}
like image 339
Spring Avatar asked Oct 28 '15 08:10

Spring


1 Answers

What you actually need is a global handler for MissingServletRequestParameterException, which is thrown by Spring when a request parameter is missing. The easiest way to tackle this problem is to use ControllerAdvice that will handle it for all your controllers.

import org.springframework.web.bind.MissingServletRequestParameterException;

@ControllerAdvice
class MissingServletRequestParameterExceptionHandler {
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleMissingParameter() {
        return "Your custom result";
    }
}

If you want to hide the missing parameter message only for a particular controller, just move handleMissingParameter method to this controller without creating the ControllerAdvice.

like image 93
Daniel Olszewski Avatar answered Sep 20 '22 06:09

Daniel Olszewski