This article will springmvc exception handling.
1, environmental constraints
- win10 64-bit operating system
- idea2018.1.5
- jdk-8u162-windows-x64
- spring4.2.4
2, the premise of restraint
- Complete annotation-based demo springmvc of https://www.jianshu.com/p/d1a84f07c98f
3, steps
1. ExceptionHandler
- Create a net.wanho.controller.ExceptionController.java in the src folder file, as follows:
@Controller
public class ExceptionController{
@ExceptionHandler(value = ArithmeticException.class)
public String test1excp()
{
System.out.println(this);
return "arithmetic";
}
@RequestMapping("/exception1")
@ResponseBody
public String exception1()
{
System.out.println(1/0)
return "exception1";
}
}
- In the WEB-INF / page / folder, create a arithmetic.jsp file, as follows:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
数学异常界面
</body>
</html>
- Start tomcat, enter in the browser http: // localhost: 8080 / exception1 , carriage returns, we will see a jump to the page arithmetic.jsp exception handling
Note: This approach is an exception for this Controller class where the ExceptionHandler .
2. Use SimpleMappingExceptionResolver
- In the spring-mvc.xml tag was added to exception handling, as follows:
<bean id="simpleMappingExceptionResolver" class=
"org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<map>
<!-- key:异常类别(非全称), 视图名称 -->
<entry key="ArithmeticException" value="arithmetic"/>
</map>
</property>
<!-- 如果在以上配置中找不到异常,则进入此默认异常 -->
<property name="defaultErrorView" value="error"/>
</bean>
- Error.jsp join in the WEB-INF / page / folder error handling page.
Note: This approach is an exception for all Controller thrown exception.
Configuration error-page
error-page depending on the return code is the ultimate way to handle exceptions.
- Add the following configuration in web.xml:
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.jsp</location>
</error-page>
- In the WEB-INF / page / folder added 404.jsp and 500.jsp
more than three ways to handle exceptions and errors is a common way to avoid the embarrassment of our program handles errors and exceptions.