springMVC中的异常处理
1) java异常结构
|-----Throwable
|-----Error
|-----Exception
|-----RuntimeException
2) java异常分类
- 编译异常
- 运行时期异常
3)如何处理异常?
dao | 不能处理,抛异常 |
---|---|
service | 不能处理,抛异常 |
controller/servlet | 必须处理,否则错误信息直接打印到浏览器 |
4)异常处理实现方式
-
**方案1:**不可行
控制层的方法写 try…catch
-
**方案2:**异常过滤器(servelt技术实现控制层)
拦截所有请求:/*
过滤器拦截所有请求:controller,servlet,jsp,html/cscs/js
-
**方案3:**使用框架自带的异常处理机制
列如:springMVC中HandlerExceptionResolver异常处理接口
1.0.0 springMVC异常处理(一) 异常实现
环境搭建:
1)导入依赖 (web.xml,springMVC.xml,)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.zonhar</groupId>
<artifactId>springmvc03_01_exception_interceptor</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- jdk版本插件,因为一般都采用全局配置,如果当前项目不使用全局就可以使用这个插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
<!--tomcat7的插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8081</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
<server>tomcat7</server>
</configuration>
</plugin>
</plugins>
</build>
</project>
springMVC.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--ioc注解扫描-->
<context:component-scan base-package="cn.zonhar"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--springMVC注解支持-->
<mvc:annotation-driven/>
</beans>
2)编写控制器(Controller)
package cn.zonhar.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 模拟异常处理
*/
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/save")
public String save(){
//模拟异常
int i =10/0;
System.out.println("用户已保存!");
return "success";
}
}
3.测试
4.如果没有用springMVC的异常处理,传统的异常处理如何实现?
package cn.zonhar.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 模拟异常处理
*/
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/save")
public String save(){
//模拟异常
try {
int i =10/0;
System.out.println("用户已保存!");
return "success";
}catch (Exception e){
return "error";
}
}
}
以上的传统方式处理异常,比较麻烦,每个方法都需要自行处理!!!
4.改为springMVC提供的异常处理机制实现异常处理(集中处理异常)
方式一:
1) 实现HandlerExceptionResolver接口
package cn.zonhar.exception;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyHandlerExceptionResolver1 implements HandlerExceptionResolver {
/**
*resolveException: 代表所有Controller的所有方法出现异常都会执行此方法
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mv =new ModelAndView();
//存放异常信息
mv.addObject("error",e.getMessage());
//判断不同异常处理方式
if(e instanceof ArithmeticException){
mv.setViewName("error");
}else if(e instanceof NullPointerException){
mv.setViewName("error2");
}else{
mv.setViewName("error");
}
return mv;
}
}
方式二:
不实现任何接口或类,在类上加@ControllerAdvice,方法上加@ExceptionHandler
package cn.zonhar.exception;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
public class MyHandlerExceptionResolver2 {
private ModelAndView mv =new ModelAndView();
/**
* 编写处理空指针异常的方法
*/
@ExceptionHandler(NullPointerException.class)
public ModelAndView handlerError1(Exception e) {
mv.addObject("error",e.getMessage());
mv.setViewName("error");
return mv;
}
/**
* 处理数学运算异常
*
* @return
*/
@ExceptionHandler(ArithmeticException.class)
public ModelAndView HandlerError2(Exception e) {
mv.addObject("error",e.getMessage());
mv.setViewName("error");
return mv;
}
@ExceptionHandler(Exception.class)
public ModelAndView handlerError3(Exception e) {
mv.addObject("error",e.getMessage());
mv.setViewName("error");
return mv;
}
}