springmvc 全局异常处理的三种方法

第一种 

通过SimpleMappingExceptionResolver类来定义,springmvc.xml内容

自定义的异常可以继承Exception类

	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 		遇到异常时默认跳转的视图   error其实是error.jsp是视图-->
		<property name="defaultErrorView" value="error"/>
<!-- 		抛出异常后在页面可用 ${errMsg.message}  读出异常信息 -->
		<property name="exceptionAttribute" value="errMsg"/>
<!-- 		自定义的异常转向页面可自定义多个而实现不同异常转向不同页面 -->
		<property name="exceptionMappings">
			<props>
				<prop key="com.samrtian.exception.CustomException">error1</prop>
			</props>
		</property>
	</bean>


第二种    

通过实现HandlerExceptionResolver接口来定义  

springmvc.xml内容

<!--     全局异常处理器 -->
<bean class="com.samrtian.exception.CustomExceptionResolver"></bean>

接口实现  CustomException是继承了Exception类的自定义异常.

public class CustomExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		// TODO Auto-generated method stub
		
		CustomException customException = null;
		if (ex instanceof CustomException) {
			customException = (CustomException)ex;
		}else{
			customException = new CustomException("未知错误!");
		}
		String errMsg = customException.getMessage(); 
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("error", errMsg);
		modelAndView.setViewName("error");
		return modelAndView;
	}
	
}


第三种

使用@ExceptionHandler 注解定义

这个更简单了直接在控制器里加入方法,但是必须跟抛异常的方法在同一个控制器里

@Controller
public class LoginAction {
	
	@ExceptionHandler(CustomException.class)
	public String catchException(CustomException e, HttpServletRequest request) {
		System.out.println("进来了");
		request.setAttribute("errMsg", "注解的异常");
		return "error";
	}

	@RequestMapping("/login.do")
	public ModelAndView login(int id) throws Exception {
		// TODO Auto-generated method stub	
		if (id == 1) {
			throw new CustomException("自定义的异常");
		}
		
		if (id == 2) {
			throw new Exception("Exception的异常");
		}

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("LoginSuccess");
		return modelAndView;
	}

个人比较偏好第一种,简单明了


猜你喜欢

转载自blog.csdn.net/samrtian/article/details/79922329
今日推荐