JSP指令(404,500页面设计)

JSP指令:

1)

<%@ page ......." %>

这个指令可以用来设置响应的页面

测试:

项目结构

jsp2.jsp

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 
 3 <%--定制错误页面--%>
 4 <%--<%@ page errorPage="error/500.jsp" %>--%>
 5 
 6 <html>
 7 <head>
 8     <title>Title</title>
 9 </head>
10 <body>
11 <%
12     int x = 1 / 0;  // 这里会报错
13 %>
14 
15 </body>
16 </html>

404界面 404.jsp

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 <img src="img/404.png" alt="找不到">
 8 
 9 </body>
10 </html>

500界面 500.jsp

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 <img src="img/500.png" alt="50">
 8 
 9 </body>
10 </html>

去web.xml注册页面:

1 <error-page>
2         <error-code>404</error-code>
3         <location>/error/404.jsp</location>
4     </error-page>
5     <error-page>
6         <error-code>500</error-code>
7         <location>/error/500.jsp</location>
8     </error-page>

测试结果:

开始时候加载不出图片,解决方案:重启IDEA

 修改路径为不存在的路径:

2)

<%@include file="">

这个指令用来提取公共页,比如网站的头部和尾部都是固定的。

但一般不用这个,用jsp标签

<jsp:include page="">

测试代码:

创建一个common文件夹来放头和尾

header.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>我是Header</h1>

footer.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>我是Footer</h1>

写一个jsp3.jsp来做测试页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<body>

<%--@include会将两个页面合二为一,如果每个页面都定义同名变量会报500错--%>
<%@include file="common/header.jsp" %>
<h1>网页主体</h1>
<%@include file="common/footer.jsp" %>

<hr>  <-- 分割线-->

<%--jsp标签--%>
<%--jsp:include 拼接页面,本质还是3个,设置同名变量互不影响--%>
<jsp:include page="common/header.jsp"/>
<h1>网页主体</h1>
<jsp:include page="common/footer.jsp"/>


</body>
</html>

测试结果:

假如用第一种方法写网页,并且在header.jsp中定义变量x=10,在jsp3.jsp中也定义x =10,会报500的错。

 第二种的话就不会,因为互相独立

原文地址:https://www.cnblogs.com/YXBLOGXYY/p/14654956.html