Article Directory
About Abnormal
- Unusual architecture:
|
|
Handling exceptions in the Spring MVC
- In Spring MVC, there is provided a mechanism for unified treatment of some abnormality, for example, by configuration, the entire project
NullPointerException
processing, then, no matter which part of the project appear abnormal, will automatically be treated in the manner of the configuration , but do not write code as one by one each method.
Preparing presentations Case
Create a project
DAY07-SpringMVC-Exception
, design request path:http://SERVER:PORT/PROJECT/ex1.do
http://SERVER:PORT/PROJECT/ex2.do
Three or more requests are made
ex1.jsp
,ex2.jsp
the page display.
使用SimpleMappingExceptionResolver
- 在Spring MVC中,有
SimpleMappingExceptionResolver
类,用于配置异常与View组件的映射关系,如果确定某种异常出现后都会显示某个View组件,则在Spring的配置文件中:
|
|
经过以上配置后,整个项目运行到任何位置,一旦出现以上配置过的异常,都会转发到匹配的View组件,在项目的各个方法中,不必再处理已经配置过的异常!
这种做法的不足在于:只要是同一种异常,都是转发到同一个View组件,无法根据实际运行状态进行更加细化的处理,例如无法提示是哪个值错误或者某些原因导致的异常。
使用@ExceptionHandler
注意:使用SimpleMappingExceptionResolver处理异常时,不可以使用@ExceptionHandler!
- 当需要统一处理异常时,可以在控制器类中自定义方法(方法名称自定义),并在方法上方添加
@ExceptionHandler
,与处理请求的方法类似,可以按需添加方法的参数,需要注意的,必须有Exception
参数:
|
|
- This approach, currently is acting on the inner processing of all requests of the controller class! On the other controller class exception is not affected!
Spring MVC Summary
- MVC solution relationship of V and C, i.e., receives a request and response;
- In the Spring configuration file, the configuration is the most important component scans and ViewResolver;
- Master key
@RequestMapping
notes, and@RequestParam
notes; - Lies in processing the request, how to obtain the requested parameters (two kinds) and the encapsulating and forwarding data (
ModelMap
); - Understanding forwarding and redirection;
Learn to use
Interceptor
;Learn to handle exceptions.
Original: Big Box Springmvc handle exceptions