案例目录结构:

Web.xml 配置:

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--设置乱码-->
<filter>
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置核心控制器-->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:Spring-*.xml</param-value>
</init-param>
<!--优先加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

第一种:使用Spring自带的异常处理机制:

ControllerWelcome:控制层:

package controller;
import exception.NameException;
import exception.PwdException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author asus
*/
@Controller
@RequestMapping("/user")
public class ControllerWelcome{
@RequestMapping("/name")
public String nameException() {
System.out.println("用户名异常!!!");
if (true) {
throw new NameException("用户名异常");
}
return "Welcome";
}
@RequestMapping("/pwd")
public String pwdException() {
System.out.println("密码异常!!!");
if (true) {
throw new PwdException("密码异常");
}
return "Welcome";
}
@RequestMapping("/other")
public String otherException() {
System.out.println(5 / 0);
return "Welcome";
}
}

定义的异常类:NameException  (OtherException、PwdException;结构都一样 都继承 RuntimeException 实现三个方法)这里列举一个

package exception;

/**
* 密码异常
* @author asus
*/
public class PwdException extends RuntimeException{ public PwdException() {
super();
} public PwdException(String message) {
super(message);
} public PwdException(String message, Throwable cause) {
super(message, cause);
}
}

定义的 exception下的 jsp 页面同样这里列举一个:(其他两个只是换了一下 h1的内容做了一下区分而已)

NameException.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>用户名异常</h1>
</body>
</html>

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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--指定Controller扫描器-->
<context:component-scan base-package="controller"/>
<!--配置试图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean> </beans>

Spring-excption.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--系统自带异常机制映射配置-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="exception.NameException">exception/NameException</prop>
<prop key="exception.PwdException">exception/PwdException</prop>
</props>
</property>
<!--默认异常页面-->
<property name="defaultErrorView" value="exception/OtherException"/>
</bean> </beans>

提示:按住  SimpleMappingExceptionResolver 进来我们的底层查看,发现有个一常量值,就是用来获取我们编写的错误信息的(存放在了request作用域下)。如下所示

 Welcome.jsp :

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--获取错误信息--%>
${exception}
</body>
</html>

 例如要访问:localhost:8080/user/name:这时页面就会跳转 Welcome.jsp 并且显示 用户名异常

第二种:自定义异常处理机制:

在上述中的 exception 包下添加我们的自定义的类:MyExceptionResolve 并且继承 AbstractHandlerExceptionResolver

MyExceptionResolve :

package exception;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 自定义异常处理机制
* @author asus
*/
public class MyExceptionResolve extends AbstractHandlerExceptionResolver {
/**
* @param request:请求
* @param response:响应
* @param handler:执行的某一Controller 控制器
* @param ex:异常信息
* @return
*/
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//默认为其他异常页面
ModelAndView modelAndView=new ModelAndView("exception/OtherException");
//判断是什么类型的异常
if(ex instanceof NameException)
{
modelAndView.setViewName("exception/NameException");
}else if(ex instanceof PwdException)
{
modelAndView.setViewName("exception/PwdException");
}
modelAndView.addObject("exception",ex);
return modelAndView;
}
}

修改我们的配置文件:Spring-excption.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--自定义的异常类:-->
<bean class="exception.MyExceptionResolve"/> </beans>

还是按照上述的 方式运行页面即可 查看效果......

第三种:使用注解实现异常处理机制:

 为了方便阅读:专门提升了一个编写注解方式的类:BaseControllerEx

package exception;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* 使用注解实现异常处理机制
* @author asus
*/
@Controller
public class BaseControllerEx {
@ExceptionHandler(NameException.class)
public ModelAndView nameEx(NameException ex)
{
ModelAndView modelAndView=new ModelAndView("exception/NameException");
modelAndView.addObject("exception",ex.getMessage());
return modelAndView;
}
@ExceptionHandler(PwdException.class)
public ModelAndView nameEx(PwdException ex)
{
ModelAndView modelAndView=new ModelAndView("exception/PwdException");
modelAndView.addObject("exception",ex.getMessage());
return modelAndView;
}
}

注解的方式就不需要 Spring-excption.xml 配置了,所以直接干掉就可以或者注释掉配置

这时我们只需要稍微改动一下我们的 ControllerWelcome 类去继承我们的注解类:

运行方式同上述一致......

分享知识-快乐自己:Spring中的(三种)异常处理机制的更多相关文章

  1. Spring 中如何自动创建代理(spring中的三种自动代理创建器)

    Spring 提供了自动代理机制,可以让容器自动生成代理,从而把开发人员从繁琐的配置中解脱出来 . 具体是使用 BeanPostProcessor 来实现这项功能. 这三种自动代理创建器 为:Bean ...

  2. java中存在三种调用机制

    1:同步调用:一种阻塞式调用,调用方要等待对方执行完毕才返回,它是一种单向调用 2:回调:一种双向调用模式,也就是说,被调用方在接口被调用时也会调用对方的接口: 3:异步调用:一种类似消息或事件的机制 ...

  3. spring配置datasource三种方式

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp34 spring配置datasource三种方式 1.使用org.spri ...

  4. SuperDiamond在JAVA项目中的三种应用方法实践总结

    SuperDiamond在JAVA项目中的三种应用方法实践总结 1.直接读取如下: @Test public static void test_simple(){ PropertiesConfigur ...

  5. js oop中的三种继承方法

    JS OOP 中的三种继承方法: 很多读者关于js opp的继承比较模糊,本文总结了oop中的三种继承方法,以助于读者进行区分. <继承使用一个子类继承另一个父类,子类可以自动拥有父类的属性和方 ...

  6. spring Bean的三种配置方式

    Spring Bean有三种配置方式: 传统的XML配置方式 基于注解的配置 基于类的Java Config 添加spring的maven repository <dependency> ...

  7. Java三大框架之——Hibernate中的三种数据持久状态和缓存机制

    Hibernate中的三种状态   瞬时状态:刚创建的对象还没有被Session持久化.缓存中不存在这个对象的数据并且数据库中没有这个对象对应的数据为瞬时状态这个时候是没有OID. 持久状态:对象经过 ...

  8. spring与mybatis三种整合方法

    spring与mybatis三种整合方法 本文主要介绍Spring与Mybatis三种常用整合方法,需要的整合架包是mybatis-spring.jar,可通过链接 http://code.googl ...

  9. Asp.Net中的三种分页方式

    Asp.Net中的三种分页方式 通常分页有3种方法,分别是asp.net自带的数据显示空间如GridView等自带的分页,第三方分页控件如aspnetpager,存储过程分页等. 第一种:使用Grid ...

  10. httpClient中的三种超时设置小结

    httpClient中的三种超时设置小结   本文章给大家介绍一下关于Java中httpClient中的三种超时设置小结,希望此教程能给各位朋友带来帮助. ConnectTimeoutExceptio ...

随机推荐

  1. HDU 4927 大数

    题意非常easy: 对于长度为n的数.做n-1遍.生成的新数列: b1=a2-a1   b2=a3-a2  b3=a4-a3 c1=b2-b1   c2=b3-b2 ans=c2-c1 最后推出公式: ...

  2. Python将JSON格式数据转换为SQL语句以便导入MySQL数据库

    前文中我们把网络爬虫爬取的数据保存为JSON格式,但为了能够更方便地处理数据.我们希望把这些数据导入到MySQL数据库中.phpMyadmin能够把MySQL数据库中的数据导出为JSON格式文件,但却 ...

  3. 身份证识别接口编写的JAVA调用示例

    此java文章是基本聚合数据证件识别接口来演示,基本HTTP POST请求上传图片并接收JSON数据来处理. 使用前你需要通过 https://www.juhe.cn/docs/api/id/153 ...

  4. ie下div模拟的表格,表头表体无法对齐

    现象:ie下,如果某个区域滚动显示表格内容(div模拟的table),表体出现滚动条的时候,会跟表头无法对齐. 解决方法:1.首先需要知道两个高度:表体最大高度height1.目前表体要显示的内容高度 ...

  5. 应用程序之TableView简单总结1

    UITableView的代理方法 修改Cell的状态 UITableView常见方法 一.UITableView的代理方法 #pragma mark 每一行的高度 - (CGFloat)tableVi ...

  6. 【Unity 3D】学习笔记三十三:游戏元素——天空盒子

    天空盒子 一般的3D游戏都会有着北京百年一遇的蓝天.让人惊叹不已.事实上天空这个效果没有什么神奇的仅仅需用到天空盒子这个组件即可.能够将天空设想成一个巨大的盒子,这个盒子将整个游戏视图和全部的游戏元素 ...

  7. NGINX下如何自定义404页面

    什么是404页面 如果碰巧网站出了问题,或者用户试图访问一个并不存在的页面时,此时服务器会返回代码为404的错误信息,此时对应页面就是404页面.404页面的默认内容和具体的服务器有关.如果后台用的是 ...

  8. python3.x中xml.etree.ElementTree解析xml举例

    1.新建xml import xml.etree.ElementTree as ETa=ET.Element('elem')c=ET.SubElement(a,'child1')c.text=&quo ...

  9. Django之站内搜索-Solr,Haystack

    java -version 不多说 solr 是java 开发的 java version "1.7.0_79" Java(TM) SE Runtime Environment ( ...

  10. CSS3 实现背景透明,文字不透明,兼容所有浏览器

    <!DOCTYPE html><html><head><meta charset="utf-8"><title>opac ...