Spring3.0.5 MVC—異常處理
作者:zuzong
簡單,清晰,夠用,異常類型與視圖的映射,自定義的任何異常類型都可以在這里和錯誤頁面進行映射,顆粒度夠細
SimpleMappingExceptionResolver
簡單,清晰,夠用,異常類型與視圖的映射,自定義的任何異常類型都可以在這里和錯誤頁面進行映射,顆粒度夠細
springmvc.xml
Xml代碼
- <bean id="webExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="defaultErrorView" value="redirect:/error.jsp?flag=defaultErrorView" />
- <property name="exceptionMappings">
- <props>
- <prop key="com.a.a.a.exception.BaseServiceException">
- redirect:/error.jsp?flag=BaseServiceException
- < span>prop>
- <prop key="java.lang.RuntimeException">
- redirect:/error.jsp?flag=RuntimeException
- < span>prop>
- < span>props>
- < span>property>
- < span>bean>
Spring 3新增的注解是異常處理,在Control類中加入
Java代碼
- @RequestMapping("exception")
- public void throwException() {
- throw new RuntimeException("This is the runtime exception");
- }
- @ExceptionHandler(Exception.class)
- public @ResponseBody String handleException(Exception ex) {
- return ex.getMessage();
- }
也可以將@ExceptionHandle抽象到BaseControl里,不過若用了SimpleMappingExceptionResolver,則@ExceptionHandle會不起作用
HandlerExceptionResolver
自定義異常實現(xiàn)
Java代碼
- public class WebExceptionResolver implements HandlerExceptionResolver {
- public ModelAndView resolveException(HttpServletRequest request,
- HttpServletResponse response, Object object, Exception e) {
- HttpSession session = request.getSession();
- session.getId();
- //處理異常
- return null;
- }
- }
springmvc.xml
Xml代碼
- <bean id="webExceptionResolver" class="com.a.a.WebExceptionResolver"/>
【編輯推薦】
- Spring Hibernate簡單討論
- OSGi與Spring:設置Spring DM開發(fā)環(huán)境
- 使用Spring DM創(chuàng)建Hello World,以及OSGi服務
- Spring MVC總結:善用注解,生活更輕松
- 概括spring hibernate集成
責任編輯:金賀
來源:
ITEYE博客