JSP——自定义404和500界面
1. 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmnls.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<error-page>
<error-code>500</error-code>
<location>/error/error500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error/error404.jsp</location>
</error-page>
</web-app>
2. JSP文件
2.1 error404.jsp
<%--
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>404</title>
</head>
<body>
<img src="${pageContext.request.contextPath}/image/404.png">
</body>
</html>
2.2 error500.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
<title>500</title>
</head>
<body>
<img src="${pageContext.request.contextPath}/image/error500.png">
</body>
</html>
2.3 index.jsp
<%@page contentType="text/html; charset=utf-8" language="java" %>
<h1>网页主题</h1>
<%=32%>
<%="abcd"%>
<% int x = 10;
System.out.println(x);%>
hh
<br>
<%=x%>
<% for (int i = 0; i < 6; i++) {%>
<br>hello jsp
<%}%>
<br>
<% x++;%>
<%=x+1%>
<%!
public double add(double a, double b) {
return a + b;
}
%>
<br>
<%= add(3.6, 9.7)%>
<br>
<%= 1/1 %>
代码中1/0,即可产生异常,出现500错误
3. 出现的问题
图片无法正常显示
无法访问到资源,可将图片的路径更改为
<img src="${pageContext.request.contextPath}/image/404.png">
4. 效果展示
404错误页面访问网址http://localhost:8080/jsp-01/1
访问一个不存在的页面/1,如图所示:
500错误页面访问网址http://localhost:8080/jsp-01/,如图所示: