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


问题内容

当需求@RequestParam未发送到请求处理程序时,是否可以自定义显示的内容?在这种情况下,我总是得到HTTP状态400的描述为“
客户端发送的请求在语法上不正确()。 ”。


问题答案:

是的,您应该有一种方法 MissingServletRequestParameterException

您可以通过以下几种方式进行操作:

1)

   @ExceptionHandler(MissingServletRequestParameterException.class)
      public String handleMyException(Exception  exception) {
       return "yourErrorViewName";
              }

2)

<error-page>
    <exception-type>org.springframework.web.bind.MissingServletRequestParameterException</exception-type>
    <location>/WEB-INF/pages/myError.jsp</location>
  </error-page>

希望能帮助到你。