跟杨春娟学SpringMVC笔记:SpringMVC异常处理之404及500的处理
完成:第一遍
1.如何实现SpringMVC异常处理之404及500的处理?
先在src/main/webapp/WEB-INF/pages/error下新建两个页面404.jsp和500.jsp
404.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>This is 404 errorPage</h2>
</body>
</html>
500.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>This is 500 errorPage</h2>
</body>
</html>
第一种方式:直接定位JSP页面
在web.xml里直接加error-page标签
<error-page>
<error-code>404</error-code>
<!--第一种方式:直接定位404.jsp页面 -->
<location>/WEB-INF/pages/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<!--第一种方式:直接定位404.jsp页面 -->
<location>/WEB-INF/pages/error/500.jsp</location>
</error-page>
第二种方式:controller跳转404.jsp或500.jsp
步骤一:在web.xml里直接加error-page标签
<error-page>
<error-code>404</error-code>
<location>/error/404Page</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500Page</location>
</error-page>
步骤二:需要写一个新的Controller类
ErrorController类
package com.adbycool.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("error")
public class ErrorController {
@RequestMapping("404Page")
public String error404() {
//pages下有个error包
return "error/404";
}
@RequestMapping("500Page")
public String error500() {
return "error/500";
}
}