zoukankan      html  css  js  c++  java
  • 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>

     案例代码下载地址:

    第一个案例:

    http://git.oschina.net/hyjcode/SpringMvc/tree/master/SpringMvc-Exception-myself?dir=1&filepath=SpringMvc-Exception-myself&oid=cfc0883b35170c567b6be8b349d8e23cae8346af&sha=d42645f75fb9384c88c64498e316d66b4295eee3

    第二个案例:

    http://git.oschina.net/hyjcode/SpringMvc/tree/master/SpringMvc-Exception-annotation?dir=1&filepath=SpringMvc-Exception-annotation&oid=35df89870b4a64301b7a5baa4960b570cee35597&sha=051a90009bd14a02431b46d4b1845ae4caf30e3b

           

  • 相关阅读:
    拖拽 上传文件
    复制文本消息
    zTree 显示为‘aa’,当选择aa时,传的参数为‘22’
    移动端 动画 启动硬件加速
    jquery 停止动画与切换
    CSS小技巧-怎样让每行多余的文字显示文省略号?
    CSS小技巧-两个盒子之间的间距问题
    CSS小技巧-为内盒子添加margin-top时,会带着父盒子一起下来,如何解决?
    小K的H5之旅-CSS基础(一)
    小K的H5之旅-HTML的基本结构与基本标签
  • 原文地址:https://www.cnblogs.com/hyjj/p/6087797.html
Copyright © 2011-2022 走看看