zoukankan      html  css  js  c++  java
  • SpringMVC框架下的异常处理

    在eclipse的javaEE环境下:导包。。。。

     1. 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
     2. @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值
     3. @ExceptionHandler 方法标记的异常有优先级的问题.
     4. @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常,  则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常
     

    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"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">
    
        <!-- 配置 SpringMVC 的 DispatcherServlet -->
        <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
        <servlet>
            <servlet-name>springDispatcherServlet</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>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <!-- Map all requests to the DispatcherServlet for handling -->
        <servlet-mapping>
            <servlet-name>springDispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        
        <!-- 配置 HiddenHttpMethodFilter: 把 POST 请求转为 DELETE、PUT 请求 -->
        <filter>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
        </filter>
        
        <filter-mapping>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    </web-app>

    spring的bean的配置文件:springmvc.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: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-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
        <!-- 配置自动扫描的包 -->
        <context:component-scan base-package="com.atguigu.springmvc"></context:component-scan>
    
        <!-- 配置视图解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
        
        <!--  
            default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,
            它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的 
            Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理
    
            一般 WEB 应用服务器默认的 Servlet 的名称都是 default.
            若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定
            
        -->
        <mvc:default-servlet-handler/>
        
        <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>    
     
        <!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 ,出异常时转到error.jsp页面-->
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionAttribute" value="ex"></property>
            <property name="exceptionMappings">
                <props>
                    <!-- key异常的全类名 ,并且可以在error页面打印异常-->
                    <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
                </props>
            </property>
        </bean>    
            
    </beans>

    异常处理类,这个是全局的,只要出现了这个异常,在显示出异常值在对应的页面上;

    package com.atguigu.springmvc.test;
    
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;
    
    
    //异常处理类,这个是全局的,只要出现了这个异常,在显示出异常值 
    @ControllerAdvice
    public class SpringMVCTestExceptionHandler {
    
        @ExceptionHandler({ArithmeticException.class})
        public ModelAndView handleArithmeticException(Exception ex){
            System.out.println("----> 出异常了: " + ex);
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("exception", ex);
            return mv;
        }
        
    }

    自定义的异常:页面会显示状态码和异常值

    package com.atguigu.springmvc.test;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ResponseStatus;
    
    //自定义的异常:页面会显示状态码和异常值
    
    //value:是一个状态码
    @ResponseStatus(value=HttpStatus.FORBIDDEN, reason="用户名和密码不匹配!")
    public class UserNameNotMatchPasswordException extends RuntimeException{
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        
    }

    handler方法:

    package com.atguigu.springmvc.test;
    
    @Controller
    public class SpringMVCTest {
    
        @Autowired
        private EmployeeDao employeeDao;
     //这个需要在springmvc.xml文件中进行配置,出现异常后转向到那个页面
        @RequestMapping("/testSimpleMappingExceptionResolver")
        public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
            String [] vals = new String[10];
            System.out.println(vals[i]);
            return "success";
        }
        
        //对spring的一些特殊异常进行处理,如超链接是get请求,而这儿是post请求,所以会出现异常,显示在页面上
        @RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
        public String testDefaultHandlerExceptionResolver(){
            System.out.println("testDefaultHandlerExceptionResolver...");
            return "success";
        }
        //类方法,的自定义异常
        @ResponseStatus(reason="测试",value=HttpStatus.NOT_FOUND)
        @RequestMapping("/testResponseStatusExceptionResolver")
        public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
            if(i == 13){
                throw new UserNameNotMatchPasswordException();
            }
            System.out.println("testResponseStatusExceptionResolver...");
            
            return "success";
        }
        
        //异常处理
        
    //    @ExceptionHandler({RuntimeException.class})
    //    public ModelAndView handleArithmeticException2(Exception ex){
    //        System.out.println("[出异常了]: " + ex);
    //        ModelAndView mv = new ModelAndView("error");
    //        mv.addObject("exception", ex);
    //        return mv;
    //    }
        
        /**
         * 1. 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
         * 2. @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值
         * 3. @ExceptionHandler 方法标记的异常有优先级的问题. 
         * 4. @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常, 
         * 则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常. 
         */
    //    @ExceptionHandler({ArithmeticException.class})
    //    public ModelAndView handleArithmeticException(Exception ex){
    //        System.out.println("出异常了: " + ex);
    //        ModelAndView mv = new ModelAndView("error");
    //        mv.addObject("exception", ex);
    //        return mv;
    //    }
        
        @RequestMapping("/testExceptionHandlerExceptionResolver")
        public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
            System.out.println("result: " + (10 / i));
            return "success";
        }
        
    }

    index.jsp页面:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
       
        <br><br>
        <a href="testExceptionHandlerExceptionResolver?i=10">Test ExceptionHandlerExceptionResolver</a>
        
        <br><br>
        <a href="testResponseStatusExceptionResolver?i=10">Test ResponseStatusExceptionResolver</a>
        
        <br><br>
        <a href="testDefaultHandlerExceptionResolver">Test DefaultHandlerExceptionResolver</a>
        
        <br><br>
        <a href="testSimpleMappingExceptionResolver?i=2">Test SimpleMappingExceptionResolver</a>
    </body>
    </html>

    出现异常转向的页面error.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
        <h4>Error Page</h4>
    
        ${requestScope.exception }
    
    </body>
    </html>
  • 相关阅读:
    mybatis
    spring mvc
    Spring Boot2
    Spring AOP
    Spring Boot1
    Spring IOC
    Multiple_LinearRegression_Test2
    Multiple_LinearRegression_Test
    Simple_LinearRegression_Test
    写决策树时遇到的坑
  • 原文地址:https://www.cnblogs.com/lxnlxn/p/5940890.html
Copyright © 2011-2022 走看看