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除. ...
随机推荐
- 升级Ubuntu 16.04 LTS后 DSL拨号上网(ppp)连接自动断开解决办法
原本在Ubuntu 15.10用拨号上网没有问题,但升级了16.04 LTS后发现原来的DSL连接不上了.主要表现为: 1.在NetworkManager里面选择DSL Connection能够尝试拨 ...
- hadoop fs -ls no such file or directory
http://blog.csdn.net/baolibin528/article/details/43650919
- [LeetCode] Wiggle Subsequence 摆动子序列
A sequence of numbers is called a wiggle sequence if the differences between successive numbers stri ...
- [LeetCode] Factorial Trailing Zeroes 求阶乘末尾零的个数
Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in log ...
- [LeetCode] Maximum Gap 求最大间距
Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...
- POJ 1979 Red and Black
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #inc ...
- VUE---Missing space before function parentheses
解决方法:
- BPM问题
1.安装XFormDesigner后编辑界面报错 解决方法:
- 《UNIX环境高级编程》笔记——3.文件IO
一.引言 说明几个I/O函数:open.read.write.lseek和close,这些函数都是不带缓冲(不带缓冲,只调用内核的一个系统调用),这些函数不输入ISO C,是POSIX的一部分: 多进 ...
- vuex 初体验
vuex是vue的状态管理工具,vue进阶从es6和npm开始,es6推荐阮一峰大神的教程. vuex学习从官方文档和一个记忆小游戏开始.本着兴趣为先的原则,我先去试玩了一把-->. Vuex ...