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除. ...
随机推荐
- Spring基础
一.Spring作用:管理项目中各种业务Bean(service类.Dao类.Action类),实例化类,属性赋值 二.Spring IOC(Inversion of Control )控制反转,也被 ...
- 【Unity Shaders】学习笔记
http://www.cnblogs.com/-867259206/p/5596698.html
- [LeetCode] Rising Temperature 上升温度
Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to ...
- [LeetCode] Spiral Matrix 螺旋矩阵
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or ...
- C#工程引用自定义目录的DLL
在App.config里配置: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-mi ...
- neo4j初次使用学习简单操作-cypher语言使用
Neo4j 使用cypher语言进行操作 Cypher语言是在学习Neo4j时用到数据库操作语言(DML),涵盖对图数据的增删改查 neo4j数据库简单除暴理解的概念: Neo4j中不存在表的概念, ...
- BZOJ 1876: [SDOI2009]SuperGCD
1876: [SDOI2009]SuperGCD Time Limit: 4 Sec Memory Limit: 64 MBSubmit: 3060 Solved: 1036[Submit][St ...
- bitset用法总结
b.any() b中是否存在置为1的二进制位? b.none() b中不存在置为1的二进制位吗? b.count() b中置为1的二进制位的个数 b.size() b中二进制位的个数 b[pos] 访 ...
- 设置session,cookies
Cookie cookie = new Cookie("username",username); cookie.setMaxAge(60 * 60 * 24 * 365 * 2); ...
- Java开发环境搭建——CentOS配置
普通用户添加到sudoers u切换到root visudo进入编辑,找到root ALL=(ALL) ALL,在后面加上myusername ALL=(ALL) ALL 配置网络sudo ...