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

时间:2012-01-28 12:07:59

标签: spring-mvc http-status-code-400

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

2 个答案:

答案 0 :(得分:18)

是的,有一种方法可以捕获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>

希望它有所帮助。

答案 1 :(得分:4)

我是如何解决我的问题的:

@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");}};
}