@Nullable protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) { try { if (ex instanceof HttpRequestMethodNotSupportedException) { return this.handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException)ex, request, response, handler); } if (ex instanceof HttpMediaTypeNotSupportedException) { return this.handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException)ex, request, response, handler); } if (ex instanceof HttpMediaTypeNotAcceptableException) { return this.handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException)ex, request, response, handler); } …… } catch (Exception var6) { if (this.logger.isWarnEnabled()) { this.logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", var6); } } return null; }
异常 | 状态码 | 说明 |
---|---|---|
HttpRequestMethodNotSupportedException | 405(Method Not Allowed) | HTTP 请求方式不支持异常 |
HttpMediaTypeNotSupportedException | 415(Unsupported Media Type) | HTTP 媒体类型不支持异常 |
HttpMediaTypeNotAcceptableException | 406(Not Acceptable) | HTTP 媒体类型不可接受异常 |
BindException | 400(Bad Request) | 数据绑定异常 |
MissingServletRequestParameterException | 400(Bad Request) | 缺少参数异常 |
ConversionNotSupportedException | 500(Internal Server Error) | 数据类型转换异常 |
TypeMismatchException | 400(Bad Request) | 类型不匹配异常 |
HttpMessageNotReadableException | 400(Bad Request) | HTTP 消息不可读异常 |
HttpMessageNotWritableException | 500(Internal Server Error) | HTTP 消息不可写异常 |
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--请求和响应的字符串过滤器--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--来处理 PUT 和 DELETE 请求的过滤器--> <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> <!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 --> <servlet> <servlet-name>dispatcherServlet</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> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--开启组件扫描--> <context:component-scan base-package="net.biancheng.c"></context:component-scan> <!-- 配置 Thymeleaf 视图解析器 --> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <!-- 视图前缀 --> <property name="prefix" value="/WEB-INF/templates/"/> <!-- 视图后缀 --> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8"/> </bean> </property> </bean> </property> </bean> <!-- 当SpringMVC中设置任何一个view-controller时,其他控制器中的请求映射将全部失效,此时需要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签--> <mvc:annotation-driven></mvc:annotation-driven> </beans>
package net.biancheng.c.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class ExceptionController { /** * 测试 DefaultHandlerExceptionResolver(Spring MVC 默认的异常处理器) * @return */ @RequestMapping(value = "/testDefaultHandlerExceptionResolver", method = RequestMethod.POST) public String testDefaultHandlerExceptionResolver() { return "success"; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>访问成功</h1> </body> </html>
图1:错误页面
17:55:58.370 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/springmvc-exception-handle-demo/testDefaultHandlerExceptionResolver", parameters={} 17:55:58.372 [http-nio-8080-exec-10] WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported] 17:55:58.372 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 405 METHOD_NOT_ALLOWED
package net.biancheng.c.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "自定义异常") public class UserNotExistException extends RuntimeException { }
属性 | 说明 |
---|---|
code |
设置异常的状态码。 code 为 @ResponseStatus 注解 value 属性的别名,与 value 属性完全等价。 |
value |
设置异常的状态码。 value 为 @ResponseStatus 注解 code 属性的别名,与 code 属性完全等价。 |
reason | 设置异常的原因或描述。 |
package net.biancheng.c.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "自定义异常") public class UserNotExistException extends RuntimeException { }
package net.biancheng.c.entity; public class User { private String userId; private String userName; private String password; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "userId='" + userId + '\'' + ", userName='" + userName + '\'' + ", password='" + password + '\'' + '}'; } }
package net.biancheng.c.controller; import net.biancheng.c.dao.UserDao; import net.biancheng.c.entity.User; import net.biancheng.c.exception.UserNotExistException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; @Controller public class UserController { @Resource private UserDao userDao; @RequestMapping("/login") public String login(String userName, Model model) { User user = userDao.getUserByUserName(userName); if (user == null) { throw new UserNotExistException(); } return "success"; } }
package net.biancheng.c.dao; import net.biancheng.c.entity.User; import org.springframework.stereotype.Repository; import java.util.*; @Repository public class UserDao { private static Map<String, User> users = null; static { users = new HashMap<String, User>(); User user = new User(); User user2 = new User(); user2.setUserId("1001"); user2.setUserName("admin"); user2.setPassword("admin"); users.put(user.getUserName(), user); users.put(user2.getUserName(), user2); } /** * 根据用户名获取用户信息 * * @param userName * @return */ public User getUserByUserName(String userName) { User user = users.get(userName); return user; } }
图2:自定义异常
package net.biancheng.c.controller; import net.biancheng.c.exception.UserNotExistException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ExceptionController2 { //控制器方法 @RequestMapping(value = "/testExceptionHandler") public String testExceptionHandler() { //发生 ArithmeticException 异常 System.out.println(10 / 0); return "success"; } //使用 @ExceptionHandler 注解定义一个异常处理方法 @ExceptionHandler(ArithmeticException.class) public String handleException(ArithmeticException exception, Model model) { //将异常信息通过 Model 放到 request 域中,以方便在页面中展示异常信息 model.addAttribute("ex", exception); //跳转到错误页 return "error"; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 出错了! <h4 th:text="${ex}"></h4> </body> </html>
图3:异常处理器
package net.biancheng.c.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ExceptionController { //控制器方法 @RequestMapping(value = "/testExceptionHandler") public String testExceptionHandler() { //发生 ArithmeticException 异常 System.out.println(10 / 0); return "success"; } //使用 @ExceptionHandler 注解定义一个异常处理方法 @ExceptionHandler(value = {Exception.class}) public String handleException(Exception exception, Model model) { //将异常信息通过 Model 放到 request 域中,以方便在页面中展示异常信息 model.addAttribute("ex", exception); //跳转到错误页 return "error"; } @ExceptionHandler(value = {RuntimeException.class}) public String handleException2(Exception exception, Model model) { //将异常信息通过 Model 放到 request 域中,以方便在页面中展示异常信息 model.addAttribute("ex", exception); //跳转到错误页 return "error-2"; } }
package net.biancheng.c.controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ExceptionControllerAdvice { @ExceptionHandler public String exceptionAdvice(Exception exception, Model model) { System.out.println("ExceptionControllerAdvice>>>>>>>>>>>>>>>>>>>"); model.addAttribute("ex", exception); return "error-2"; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> error-2 出错了! <h4 th:text="${ex}"></h4> <!--<p>code:<span th:text="${ext.code}"></span></p>--> <!--<p>path:<span th:text="${ext.message}"></span></p>--> </body> </html>
图4:全局异常处理
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!--properties的键表示处理器方法执行过程中出现的异常 properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面--> <prop key="net.biancheng.c.exception.UserNotExistException">error-3</prop> </props> </property> <!-- exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享--> <property name="exceptionAttribute" value="ex"></property> </bean>
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> error-3 出错了! <h4 th:text="${ex}"></h4> </body> </html>
图5:SimpleMappingExceptionResolver 全局异常处理
本文链接:http://task.lmcjl.com/news/15652.html