SpringMVC基础-12-异常处理

代码示例

ExceptionTestController.java:

 1 package com.atguigu.controller;
 2 
 3 import org.springframework.http.HttpStatus;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.ExceptionHandler;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RequestMethod;
 8 import org.springframework.web.bind.annotation.RequestParam;
 9 import org.springframework.web.bind.annotation.ResponseStatus;
10 import org.springframework.web.servlet.ModelAndView;
11 
12 @Controller
13 public class ExceptionTestController {
14 
15     // @ResponseStatus(reason="反正我错误了。。。",value=HttpStatus.NOT_EXTENDED)
16     @RequestMapping("/handle01")
17     public String handle01(Integer i) {
18         System.out.println("handle01....");
19         System.out.println(10 / i);
20         return "success";
21     }
22 
23     @RequestMapping("/handle02")
24     public String handle02(@RequestParam("username") String username) {
25         if (!"admin".equals(username)) {
26             
27             System.out.println("登陆失败....");
28             throw new UserNameNotFoundException();
29         }
30         System.out.println("登陆成功!。。。");
31         return "success";
32     }
33     
34     @RequestMapping(value="/handle03",method=RequestMethod.POST)
35     public String handle03(){
36         return "success";
37     }
38     
39     @RequestMapping("/handle04")
40     public String handle04(){
41         System.out.println("handle04");
42         String str = null;
43         System.out.println(str.charAt(0));
44         return "success";
45     }
46 
47     /**
48      * 告诉SpringMVC这个方法专门处理这个类发生的异常 1、给方法上随便写一个Exception,用来接受发生的异常
49      * 2、要携带异常信息不能给参数位置写Model; 3、返回ModelAndView就行了;
50      * 4、如果有多个@ExceptionHandler都能处理这个异常,精确优先 5、全局异常处理与本类同时存在,本类优先;
51      */
52 //    @ExceptionHandler(value = { Exception.class })
53 //    public ModelAndView handleException01(Exception exception) {
54 //        System.out.println("本类的:handleException01..." + exception);
55 //        //
56 //        ModelAndView view = new ModelAndView("myerror");
57 //        view.addObject("ex", exception);
58 //        // 视图解析器拼串
59 //        return view;
60 //    }
61 
62 }

MyJiZhongException.java:

 1 package com.atguigu.controller;
 2 
 3 import org.springframework.web.bind.annotation.ControllerAdvice;
 4 import org.springframework.web.bind.annotation.ExceptionHandler;
 5 import org.springframework.web.servlet.ModelAndView;
 6 
 7 /**
 8  * 集中处理所有异常
 9  * @author lfy
10  * 
11  * 1、集中处理所有异常的类加入到ioc容器中
12  * 2、@ControllerAdvice专门处理异常的类
13  */
14 @ControllerAdvice
15 public class MyJiZhongException {
16     
17     @ExceptionHandler(value={ArithmeticException.class})
18     public ModelAndView handleException01(Exception exception){
19         System.out.println("全局的:handleException01..."+exception);
20         //
21         ModelAndView view = new ModelAndView("myerror");
22         view.addObject("ex", exception);
23         //视图解析器拼串
24         return view;
25     }
26     
27 //    @ExceptionHandler(value={Exception.class})
28 //    public ModelAndView handleException02(Exception exception){
29 //        System.out.println("全局的:handleException02..."+exception);
30 //        //
31 //        ModelAndView view = new ModelAndView("myerror");
32 //        view.addObject("ex", exception);
33 //        //视图解析器拼串
34 //        return view;
35 //    }
36 
37 }

UserNameNotFoundException.java:

 1 package com.atguigu.controller;
 2 
 3 import org.springframework.http.HttpStatus;
 4 import org.springframework.web.bind.annotation.ResponseStatus;
 5 
 6 
 7 @ResponseStatus(reason="用户被拒绝登陆",value=HttpStatus.NOT_ACCEPTABLE)
 8 public class UserNameNotFoundException extends RuntimeException {
 9 
10     private static final long serialVersionUID = 1L;
11     
12 }

springmvc.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 9 
10     <context:component-scan base-package="com.atguigu"></context:component-scan>
11     
12     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
13         <property name="prefix" value="/WEB-INF/pages/"></property>
14         <property name="suffix" value=".jsp"></property>
15     </bean>
16 
17     <mvc:default-servlet-handler/>
18     <mvc:annotation-driven></mvc:annotation-driven>
19     
20     <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
21         <!-- exceptionMappings:配置哪些异常去哪些页面 -->
22         <property name="exceptionMappings">
23             <props>
24                 <!-- key:异常全类名;value:要去的页面视图名; -->
25                 <prop key="java.lang.NullPointerException">myerror</prop>
26             </props>
27         </property>
28         <!--指定错误信息取出时使用的key  -->
29         <property name="exceptionAttribute" value="ex"></property>
30     </bean>
31 
32 </beans>

web.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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">
 3   <display-name>12.SpringMVC_exception</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list>
12   <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
13     <servlet>
14         <servlet-name>springDispatcherServlet</servlet-name>
15         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16         <init-param>
17             <param-name>contextConfigLocation</param-name>
18             <param-value>classpath:springmvc.xml</param-value>
19         </init-param>
20         <load-on-startup>1</load-on-startup>
21     </servlet>
22 
23     <!-- Map all requests to the DispatcherServlet for handling -->
24     <servlet-mapping>
25         <servlet-name>springDispatcherServlet</servlet-name>
26         <url-pattern>/</url-pattern>
27     </servlet-mapping>
28     
29     <!-- 字符编码Filter -->
30     <filter>
31         <filter-name>CharacterEncodingFilter</filter-name>
32         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
33         <init-param>
34             <param-name>encoding</param-name>
35             <param-value>utf-8</param-value>
36         </init-param>
37         <init-param>
38             <param-name>forceEncoding</param-name>
39             <param-value>true</param-value>
40         </init-param>
41     </filter>
42     <filter-mapping>
43         <filter-name>CharacterEncodingFilter</filter-name>
44         <url-pattern>/*</url-pattern>
45     </filter-mapping>
46     
47     <!-- 支持Rest风格转换的filter -->
48     <filter>
49         <filter-name>HiddenHttpMethodFilter</filter-name>
50         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
51     </filter>
52     <filter-mapping>
53         <filter-name>HiddenHttpMethodFilter</filter-name>
54         <url-pattern>/*</url-pattern>
55     </filter-mapping>
56 </web-app>

index.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 <%
 9     pageContext.setAttribute("ctp", request.getContextPath());
10 %>
11 </head>
12 <body>
13 
14 <a href="${ctp }/handle01?i=10">test01-哈哈</a><br/>
15 <a href="${ctp }/handle02?username=admin">handle02</a><br/>
16 <a href="${ctp }/handle03">handle03</a><br/>
17 <a href="${ctp }/handle04">handle04</a>
18 </body>
19 </html>

myerror.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 <h1>出错啦!</h1>
11 <h2>错误信息:${ex }-${exception }</h2>
12 </body>
13 </html>

success.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 <%
11 System.out.println("success.jsp....");
12 %>
13 <h1>成功!</h1>
14 </body>
15 </html>

猜你喜欢

转载自www.cnblogs.com/116970u/p/13180192.html
今日推荐