SpingMvc中的异常处理
一.处理异常的方式
Spring3.0中对异常的处理方法一共提供了两种:
第一种是使用HandlerExceptionResolver接口。
第二种是在Controller类内部使用@ExceptionHandler注解。
二.使用HandlerExceptionResolver接口实现异常处理
直接切入架构,配置的什么都不说了,相信这个大家都会
使用这种方式只需要实现resolveException方法,该方法返回一个ModelAndView对象,在方法内部对异常的类型进行判断,然后返回合适的ModelAndView对象,如果该方法返回了null,则Spring会继续寻找其他的实现了HandlerExceptionResolver 接口的Bean。换句话说,Spring会搜索所有注册在其环境中的实现了HandlerExceptionResolver接口的Bean,逐个执行,直到返回了一个ModelAndView对象。

案例描述:
打开首页看到的是注册页面:

既然是案例,我在这里就伪造了注册的时候用户名只能是hyj 密码的要求是只能大于6位数。
用户名错误:


密码错误:


用户名和密码都填写正确,跳到注册成功页面


看代码吧:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<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:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>regist.jsp</welcome-file>
</welcome-file-list>
</web-app>
regist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="exception.do" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>用户密码:</td>
<td><input type="password" name="pwd" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="注册"/></td>
</tr>
</table>
</form>
</body>
</html>
nameerroe.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>用户名错误页面</title>
</head>
<body>
用户名错误<br/>
错误信息:${ex.message}
</body>
</html>
pwderror.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>密码错误页面</title>
</head>
<body>
密码错误
错误信息:${ex.message}
</body>
</html>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>成功</title>
</head>
<body>
注册成功
</body>
</html>
spingmvc.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" 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/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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 注解包扫描器 -->
<context:component-scan base-package="cn.controller"></context:component-scan>
<bean class="cn.exception.MyException"></bean>
</beans>
实体类:User.java
package cn.entity;
public class User {
private String name;
private String pwd;
public User(String name, String pwd) {
super();
this.name = name;
this.pwd = pwd;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
NameException.java
package cn.exception;
public class NameException extends UserException{
public NameException() {
super();
}
public NameException(String message) {
super(message);
}
}
package cn.exception;
public class PwdException extends UserException {
public PwdException() {
super();
}
public PwdException(String message) {
super(message);
}
}
UsersException.java
package cn.exception;
public class UserException extends Exception {
public UserException() {
super();
}
public UserException(String message) {
super(message);
}
}
MyException.java
package cn.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/**
* 实现HandlerExceptionResolver接口,进行异常处理
* @author hyj
*
*/
public class MyException implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object arg2, Exception ex) {
ModelAndView mv=new ModelAndView();
mv.addObject("ex", ex);
mv.setViewName("error.jsp");
if(ex instanceof NameException){
mv.setViewName("nameerroe.jsp");
}
if(ex instanceof PwdException){
mv.setViewName("pwderror.jsp");
}
return mv;
}
}
MyController.java
package cn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.entity.User;
import cn.exception.NameException;
import cn.exception.PwdException;
@Controller
public class MyController {
@RequestMapping(value="/exception.do")
public String returnObject(User user) throws Exception{
if(!"hyj".equals(user.getName())){
throw new NameException("用户名错误");
}
if(user.getPwd().length()<6){
throw new PwdException("密码必须大于6位数");
}
return "success.jsp";
}
}
二.使用注解@ExceptionHandler实现异常处理

上面红色框的部分是要读者在前面项目中做更改的地方。
加上一个BaseController.java类:
package cn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import cn.exception.NameException;
import cn.exception.PwdException;
@Controller
public class BaseController {
/**
* 用户名异常
* @param ex
* @return
*/
@ExceptionHandler(NameException.class)
public ModelAndView HandlerNameException(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("ex", ex);
mv.setViewName("nameerroe.jsp");
return mv;
}
/**
* 密码异常
* @param ex
* @return
*/
@ExceptionHandler(PwdException.class)
public ModelAndView HandlerPwdException(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("ex", ex);
mv.setViewName("pwderror.jsp");
return mv;
}
/**
* 如果除了用户名异常,密码异常,其余的异常将被这个方法捕获到
* @param ex
* @return
*/
@ExceptionHandler(Exception.class)
public ModelAndView HandlerException(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("ex", ex);
mv.setViewName("error.jsp");
return mv;
}
}
在MyController继承BaseController
package cn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.entity.User;
import cn.exception.NameException;
import cn.exception.PwdException;
@Controller
public class MyController extends BaseController{
@RequestMapping(value="/exception.do")
public String returnObject(User user) throws Exception{
if(!"hyj".equals(user.getName())){
throw new NameException("用户名错误");
}
if(user.getPwd().length()<6){
throw new PwdException("密码必须大于6位数");
}
return "success.jsp";
}
}
spingmvc.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" 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/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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 注解包扫描器 -->
<context:component-scan base-package="cn.controller"></context:component-scan>
</beans>
案例代码下载地址:
第一个案例:
第二个案例:
SpingMvc中的异常处理的更多相关文章
- 【repost】JS中的异常处理方法分享
我们在编写js过程中,难免会遇到一些代码错误问题,需要找出来,有些时候怕因为js问题导致用户体验差,这里给出一些解决方法 js容错语句,就是js出错也不提示错误(防止浏览器右下角有个黄色的三角符号,要 ...
- 第65课 C++中的异常处理(下)
1. C++中的异常处理 (1)catch语句块可以抛出异常 ①catch中获捕的异常可以被重新抛出 ②抛出的异常需要外层的try-catch块来捕获 ③catch(…)块中抛异常的方法是throw; ...
- Swift基础--Swift中的异常处理
Swift中的异常处理 OC中的异常处理:方法的参数要求传入一个error指针地址,方法执行完后,如果有错误,内部会给error赋值 Swift中的异常处理:有throws的方法,就要try起来,然后 ...
- ASP.NET Web API 中的异常处理(转载)
转载地址:ASP.NET Web API 中的异常处理
- Struts2中的异常处理
因为在Action的execute方法声明时就抛出了Exception异常,所以我们无需再execute方法中捕捉异常,仅需在struts.xml 中配置异常处理. 为了使用Struts2的异常处理机 ...
- C++中的异常处理(三)
C++中的异常处理(三) 标签: c++C++异常处理 2012-11-24 23:00 1520人阅读 评论(0) 收藏 举报 分类: 编程常识(2) 版权声明:本文为博主原创文章,未经博主允许 ...
- C++中的异常处理(二)
C++中的异常处理(二) 标签: c++C++异常处理 2012-11-24 20:56 1713人阅读 评论(2) 收藏 举报 分类: C++编程语言(24) 版权声明:本文为博主原创文章,未经 ...
- C++中的异常处理(一)
来自:CSDN 卡尔 后续有C++中的异常处理(二)和C++中的异常处理(三),C++中的异常处理(二)是对动态分配内存后内部发生错误情况的处理方法,C++中的异常处理(三)中是使用时的异常说明. ...
- Java中实现异常处理的基础知识
Java中实现异常处理的基础知识 异常 (Exception):发生于程序执行期间,表明出现了一个非法的运行状况.许多JDK中的方法在检测到非法情况时,都会抛出一个异常对象. 例如:数组越界和被0除. ...
随机推荐
- hbase 权威指南笔记(二)
这次我们先来讨论hbase的重试机制,为什么呐,因为最近公司最近也在做这方面的优化,所以就今天研究的一些成功记录一下. configuration.setInt("hbase.client. ...
- Logcat使用总结
不建议用System.out.println(), 因为使用syso导致日志打印不可控制.打印时间无法确定.不能添加过滤器.日志没有级别区分等为题. Android中的日志工具类是Log(androi ...
- 原生Ajax
使用原生Ajax 验证用户名是否被注册 创建出注册信息: <h1>注册信息</h1><input type="text" name="txt ...
- Centos7 升级内核和应用TCP BBR 算法
首先确认目前使用内核 uname -r rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org rpm -Uvh http://www.e ...
- 数组,集合分割函数,join()
join函数定义如下: // 串联类型为 System.String 的 System.Collections.Generic.IEnumerable<T> 构造集合的成员,其中在每个成员 ...
- [LeetCode] Design Hit Counter 设计点击计数器
Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...
- [LeetCode] Shortest Palindrome 最短回文串
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. ...
- [LeetCode] Find Minimum in Rotated Sorted Array 寻找旋转有序数组的最小值
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ...
- FineUI(专业版)v3.1发布(ASP.NET控件库)!
FineUI(专业版)v3.1 正式发布,60多项更新,官网示例多达 690 个,新增 30 个页面加载动画! 自 2008 年 4 月发布第一个版本,我们持续更新了 126 个版本,拥有 16000 ...
- 利用HttpWebRequest实现实体对象的上传
一 简介 HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择.它们支持一系列有用的属性.这两个类位 于System.Net命名空间,默认情况下这个类对 ...