HTTP 400的Spring MVC自定义消息 [英] Spring MVC custom message for HTTP 400
问题描述
我有以下几种SprigMVC方法,返回ModelAndView或Responsebody.当用户向这些网址请求缺少必需参数的请求时,他们自然会收到消息不存在必需的字符串参数'id'" .
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".
从安全角度看,我想隐藏用户的详细说明消息.因此,黑客不容易知道缺少的参数,并且会在没有任何描述的情况下得到400错误.这是可以通过spring配置/Spring Security实现的,还是我必须手动重构所有方法才能以某种方式返回自定义消息.
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";
}
推荐答案
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";
}
}
如果只想为特定控制器隐藏缺少的参数消息,只需将handleMissingParameter
方法移至该控制器,而不创建ControllerAdvice.
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.
这篇关于HTTP 400的Spring MVC自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!