异常处理两种方式:
一、使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
直接在spring-mvc.xml中进行配置:
<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="/error.jsp"/>
<property name="exceptionMappings">
<map>
<entry key="java.lang.ClassCastException" value="/error.jsp"/>
<entry key="V_异常处理.异常.自定义异常" value="/error.jsp"/>
</map>
</property>
</bean>
二、自定义异常处理器
1、通过实现HandlerExceptionResolver自定义异常处理器:
public class MyExceptionResolver implements HandlerExceptionResolver {
/*
参数Exception:异常对象
返回值ModelAndView:跳转到错误视图信息
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if(e instanceof 自定义异常){
modelAndView.addObject("info","自定义异常");
}else if(e instanceof ClassCastException){
modelAndView.addObject("info","类转换异常");
}
modelAndView.setViewName("error.jsp");
return modelAndView;
}
}
2、在spring-mvc.xml中配置异常处理器:
<!-- 自定义异常处理器 -->
<bean class="V_异常处理.MyExceptionResolver"/>
3、编写异常页面error.jsp...
4、测试异常跳转:
@Controller
public class exceptionController {
@Autowired
private 各种异常 exce;
@RequestMapping(value = "/V")
public String show() throws FileNotFoundException, 自定义异常 {
System.out.println("show running......");
exce.ex1();
//exce.ex2();
//exce.ex3();
//exce.ex4();
//exce.ex5();
return "index.jsp";
}
}