预期异常和运行异常,前者通过捕获,后者通过规范代码开发、测试等手段减少发生概率。
系统dao层、service层、controller层出现都可通过throws Exception向上抛出,最终由SpringMvc前端控制器交由异常处理器进行异常处理。
SpringMvc项目异常处理两种方式
1、使用SpringMvc提供的简单异常处理器SimpleMappingExceptionResolver简单映射异常处理器。这种是当产生响应的异常后会跳转到响应的页面,需在spring-mvc.xml中配置。
2、实现Spring的异常处理接口HandlerExceptionResolver,自定义自己的异常处理器。
简单异常处理器SimpleMappingExceptionResolver
创建mavenWeb项目,pom文件引入springMvc依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
</dependencies>
web.xml配置前端控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置SpringMVC的前端控制器:
配置一个servlet,类选择第三方org.springframework的DispatcherServlet
配置该类,且路径为拦截所有来作为springMvc的前端控制器servlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param><!--该servlet的初始化参数-->
<!--spring-mvc.xml是怎么加载的呢
spring-mvc.xml是怎么加载的呢
类似web.xml中的<context-param>application域的全局初始化参数。
这里下面配置初始化参数spring-mvc.xml名称即为web.xml中该DispatcherServlet的servlet的init初始化参数来提供,
以便org的DispatcherServlet根据这个servlet的init初始化参数去加载springMVC的配置文件,
继而IOC出controller(特有行为)实例提供给前端控制器DispatcherServlet(共有行为)使用。
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup><!--loadOnStartup=负整数或不加默认第一次访问该servlet执行时创建servlet对象并初始化
loadOnStartup为0或正整数时,web服务器启动时创建servlet对象,数字越小,优先级越高-->
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern><!-- 配置该servlet的路径为拦截所有/,虽会覆盖tomcat静态资源访问路径,但现在没有静态资源html之类,只有jsp动态页面。-->
</servlet-mapping>
</web-app>
com.kdy.exception中MyException
public class MyException extends Exception{
}
com.kdy.service.impl中DemoServiceImpl
@Service
public class DemoServiceImpl implements DemoService {
@Override
public void show1() {
System.out.println("抛出异常转换类型...");
Object str = "zhangsan";
Integer num =(Integer) str;
}
@Override
public void show2() {
System.out.println("抛出除零异常");
int i = 1/0;
}
@Override
public void show3() throws FileNotFoundException {
System.out.println("文件找不到异常...");
InputStream in = new FileInputStream("C:/xxx/xxx/xx.txt");
}
@Override
public void show4() {
System.out.println("空指针异常");
String str = null;
str.length();
}
@Override
public void show5() throws MyException {
System.out.println("自定义异常");
throw new MyException();
}
}
com.kdy.controller中DemoController
@Controller
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping("/show1")
public String show1(){
System.out.println("show running1...");
demoService.show1();
return "index";
}
@RequestMapping("/show2")
public String show2(){
System.out.println("show running2...");
demoService.show2();
return "index";
}
@RequestMapping("/show3")
public String show3() throws FileNotFoundException {
System.out.println("show running3...");
demoService.show3();
return "index";
}
@RequestMapping("/show4")
public String show4(){
System.out.println("show running4...");
demoService.show4();
return "index";
}
@RequestMapping("/show5")
public String show5() throws MyException {
System.out.println("show running5...");
demoService.show5();
return "index";
}
}
resource下spring-mvc.xml中配置异常处理器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!--Controller的组件扫描-->
<context:component-scan base-package="com.kdy"></context:component-scan>
<!--配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property><!--前缀-->
<property name="suffix" value=".jsp"></property><!--后缀-->
</bean>
<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--<property name="defaultErrorView" value="error"/>--><!--默认异常视图:所有的Exception都走这个,这里由于上面写了视图解析器的前后缀,会把error拼接为/jsp/error.jsp-->
<property name="exceptionMappings">
<map>
<entry key="java.lang.ClassCastException" value="error1"/>
<entry key="java.lang." value="error1"/>
<entry key="java.lang.ClassCastException" value="error1"/><!--类转换异常-->
<entry key="java.lang.ArithmeticException" value="error2"/><!--除零异常-->
<entry key="java.io.import java.io.FileNotFoundException;" value="error3"/><!--文件找不到异常-->
<entry key="java.lang.NullPointerException" value="error4"/><!--空指针异常-->
<entry key="com.kdy.exception.MyException" value="error5"/><!--自定义异常-->
</map>
</property>
</bean>
</beans>
webapp下jsp的创建index.jsp
<h1>index.jsp~~~hello</h1>
webapp下jsp的创建error.jsp
<h1>通用的错误提示页面~</h1>
webapp下jsp的创建error1.jsp
<h1>类型转换异常~</h1>
webapp下jsp的创建error2.jsp
<h1>除零算数异常~</h1>
webapp下jsp的创建error3.jsp
<h1>文件找不到异常~</h1>
webapp下jsp的创建error4.jsp
<h1>空指针异常异常~</h1>
webapp下jsp的创建error5.jsp
<h1>自定义异常~</h1>
分别访问即可:http://localhost:8080/SpringException/show1... ...
自定义异常处理器,实现HandlerExceptionResolver接口
上面案例,pom文件加上servlet依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
com.kdy.resolver中创建MyExceptionResolver实现HandlerExceptionResolver接口
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if (e instanceof ClassCastException){
modelAndView.addObject("info","类转换异常");
}else if(e instanceof ArithmeticException){
modelAndView.addObject("info","除零算数异常");
}else if(e instanceof FileNotFoundException){
modelAndView.addObject("info","文件找不到异常");
}else if(e instanceof NullPointerException){
modelAndView.addObject("info","空指针异常");
}else if(e instanceof MyException){
modelAndView.addObject("info","自定义异常");
}
modelAndView.setViewName("error");
return modelAndView;
}
}
resource下spring-mvc.xml中配置自定义异常处理器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!--Controller的组件扫描-->
<context:component-scan base-package="com.kdy"></context:component-scan>
<!--配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property><!--前缀-->
<property name="suffix" value=".jsp"></property><!--后缀-->
</bean>
<!--配置异常处理器-->
<!-- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!–<property name="defaultErrorView" value="error"/>–><!–默认异常视图:所有的Exception都走这个,这里由于上面写了视图解析器的前后缀,会把error拼接为/jsp/error.jsp–>
<property name="exceptionMappings">
<map>
<entry key="java.lang.ClassCastException" value="error1"/>
<entry key="java.lang." value="error1"/>
<entry key="java.lang.ClassCastException" value="error1"/><!–类转换异常–>
<entry key="java.lang.ArithmeticException" value="error2"/><!–除零异常–>
<entry key="java.io.import java.io.FileNotFoundException;" value="error3"/><!–文件找不到异常–>
<entry key="java.lang.NullPointerException" value="error4"/><!–空指针异常–>
<entry key="com.kdy.exception.MyException" value="error5"/><!–自定义异常–>
</map>
</property>
</bean>-->
<!--自定义异常处理器-->
<bean class="com.kdy.resolver.MyExceptionResolver"/>
</beans>
webapp的jsp中error.jsp改为
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>error</title>
</head>
<body>
error通用页面~~~~~~
异常类型为${info}
</body>
</html>