配置@PathVariable类型不匹配的错误页面
假设我有一个控制器:
@Controller public class SomeController { @RequestMapping(value = "{id}/object.do") public String showObject(@PathVariable("id") Integer id, HttpServletRequest request) { //do smth return "somePage"; } }
当“id”不是数字,但字符串如“aaa / object.do”时,Tomcat会向我显示错误 – “客户端发送的请求在语法上是不正确的”。
有没有办法配置一个错误页面,只有当“id”路径变量的类型不正确时才会显示?
您可以使用@ExceptionHandler处理此特定错误(我怀疑它是TypeMismatchException )
@ExceptionHandler(TypeMismatchException.class) public ModelAndView handleTypeMismatchException(TypeMismatchException ex) { //TODO log // Return something reasonable to the end user. ... }
请注意, @ExceptionHandler
基本上具有与通常的处理程序几乎相同的function:
与使用@RequestMapping注释注释的标准控制器方法非常相似,@ ExceptionHandler方法的方法参数和返回值非常灵活。