springMVC实现全局异常(完整demo)
程序员文章站
2023-12-22 16:20:16
...
springMVC实现全局异常(完整demo)
一.为什么会有全局异常
在工作过程中,为了更好的处理业务中出现的异常,经常会使用自定义异常的方式,但是过多的抛出自定义异常,并try{}catch(){} 会使代码看起来臃肿、冗余,那么全局异常便应用而出了,全局异常很好的解决了这些问题。
二.springMVC实现全局异常的3中方式
- 使用Spring MVC提供的SimpleMappingExceptionResolver
- 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器
- 使用@ExceptionHandler注解实现异常处理
笔者这里提供的是第二种,通过实现HandlerExceptionResolver接口实现全局异常,废话少说直接上代码
1.创建maven web项目
2.pom中添加依赖 mvc依赖 web依赖 servlet依赖
<?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>com.shsxt</groupId>
<artifactId>springmvc01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>web Maven Webapp</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring web 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- spring mvc 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- web servlet 依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<!-- jetty 插件 -->
<build>
<finalName>web</finalName>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.25</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<-- 项目访问路径 如:localhost:8000/web -->
<contextPath>/web</contextPath>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.自定义异常类
package cn.cui.test;
//自定义异常类 继承RuntimeException
public class LoginException extends RuntimeException{
private Integer code = 300;
private String msg = "参数异常";
public LoginException() {
super();
}
public LoginException(String msg) {
super("参数异常");
this.msg = msg;
}
public LoginException(Integer code, String msg) {
super();
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
4.编写全局异常类
package cn.cui.test;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/**
* 实现HandlerExceptionResolver接口 重写resolveException方法
* 通过@Component表示捕获异常后执行这个类 或者可以通过在 mvc配置文件中加入
* <bean *id="handlerExceptionResolver" class="cn.cui.test.GlobalException"/>
*
**/
@Component
public class GlobalException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(
javax.servlet.http.HttpServletRequest httpServletRequest,
javax.servlet.http.HttpServletResponse httpServletResponse,
Object o, Exception e) {
//通过 instanceof 方法判断捕获的异常是否是自定义的LoginException异常
if (e instanceof LoginException)
System.out.println(((LoginException) e).getMsg()+":"+((LoginException) e).getCode());
return null;
}
}
5.spring-context配置文件
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 扫描com.shsxt.controller 下包 -->
<context:component-scan base-package="cn.cui.test" />
<!-- mvc 请求映射 处理器与适配器配置-->
<mvc:annotation-driven/>
<!--配置视图解析器 默认的视图解析器- -->
<bean id="defaultViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="contentType" value="text/html" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<-- 全局异常类中没有配置component 就配置这个bean -->
<bean id="handlerExceptionResolver" class="cn.cui.test.GlobalException"/>
</beans>
6.web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 表示容器启动时 加载上下文配置 这里指定spring 相关配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:*.xml</param-value>
</context-param>
<!-- 启用spring容器环境上下文监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 编码过滤 utf-8 -->
<filter>
<description>char encoding filter</description>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- servlet请求分发器 -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-context.xml</param-value>
</init-param>
<!-- 表示启动容器时初始化该Servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<!-- 这是拦截请求, /代表拦截所有请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
7.抛出异常测试类
package cn.cui.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ProductException {
@RequestMapping("/test")
public void testEx(){
if (true)
throw new LoginException(200,"未登录");
}
}
8.启动项目
9.本地浏览器访问
执行操作了全局异常的打印方法。