如何在Spring MVC中自定义@RequestParam错误400响应

rus*_*tyx 15 spring-mvc http-status-code-400

有没有办法自定义在@RequestParam未将请求发送到请求处理程序时显示的内容?我总是得到HTTP状态400的描述" 客户端发送的请求在语法上是不正确的(). "在这种情况下.

dan*_*nik 18

是的,有一种方法你应该抓住 MissingServletRequestParameterException

您可以通过以下几种方式实现:

1)

   @ExceptionHandler(MissingServletRequestParameterException.class)
      public String handleMyException(Exception  exception) {
       return "yourErrorViewName";
              }  
Run Code Online (Sandbox Code Playgroud)

2)

<error-page>
    <exception-type>org.springframework.web.bind.MissingServletRequestParameterException</exception-type>
    <location>/WEB-INF/pages/myError.jsp</location>
  </error-page>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


Jan*_*ani 5

我如何解决我的问题:

@ResponseBody
@ExceptionHandler(MissingServletRequestParameterException.class)
public Object missingParamterHandler(Exception exception) {
    // exception handle while specified arguments are not available requested service only. it handle when request is as api json service       
    return  new HashMap() {{ put("result", "failed"); put("type", "required_parameter_missing");}};
} 
Run Code Online (Sandbox Code Playgroud)