JSP學習(二)JSP指令
JSP指令
JSP指令(directive)是為JSP引擎而設計的,它們並不直接產生任何可見輸出,而只是告訴引擎如何處理JSP頁面中的其余部分。
JSP指令的基本語法格式:<%@ 指令 屬性名="值" %>
三個指令:
- page指令
- Include指令
- taglib指令
一、Page指令
JSP 2.0規範中定義的page指令的完整語法:
<%@ page [ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*}, ..." ] [ session="true | false" ] [ buffer="none | 8kb | sizekb" ] [ autoFlush="true | false" ] [ isThreadSafe="true | false" ] [ info="text" ] [ errorPage="relative_url" ] [ isErrorPage="true | false" ] [ contentType="mimeType [ ;charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ] [ pageEncoding="characterSet | ISO-8859-1" ] [ isELIgnored="true | false" ] %>
例如:
<%@ language="java" page import="java.util.*,java.io.*,java.sql.*" errorPage="/ErrorPage/error.jsp" pageEncoding="UTF-8" isErrorPage="true"%>
一般情況下exception對象在Jsp頁面中是獲取不到的,只有設置page指令的isErrorPage屬性為"true"(默認為false)
在web.xml中使用<error-page>標簽為整個web應用設置錯誤處理頁面:
- 可以在web.xml文件中使用<error-page>元素為整個Web應用程序設置錯誤處理頁面。
- <error-page>元素有3個子元素,<error-code>、<exception-type>、<location>
- <error-code>子元素指定錯誤的狀態碼,例如:<error-code>404</error-code>
- <exception-type>子元素指定異常類的完全限定名,例如:<exception-type>java.lang.ArithmeticException</exception-type>
- <location>子元素指定以“/”開頭的錯誤處理頁面的路徑,例如:<location>/ErrorPage/404Error.jsp</location>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 針對500錯誤的處理頁面 --> <error-page> <error-code>4500</error-code> <location>/ErrorPage/500Error.jsp</location> </error-page> </web-app>
500Error.jsp(定制的錯誤頁面的size最好超過1024bytes,否則IE瀏覽器可能無法跳轉)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <title>500(服務器錯誤)錯誤友好提示頁面</title> <!-- 3秒鐘後自動跳轉回首頁 --> <meta http-equiv="refresh" content="3;url=${pageContext.request.contextPath}/index.jsp"> </head> <body> <img alt="對不起,服務器出錯了,請聯系管理員解決!" src="${pageContext.request.contextPath}/img/500Error.png"/><br/> 3秒鐘後自動跳轉回首頁,如果沒有跳轉,請點擊<a href="${pageContext.request.contextPath}/index.jsp">這裏</a> </body> </html>
二、include指令
語法:<%@ include file="relativeURL"%>,其中的file屬性用於指定被引入文件的路徑。路徑以“/”開頭,表示代表當前web應用。
把別的文件內容包含到自身頁面的<j@include>語句就叫作靜態包含。
<jsp:include>指令為動態包含,如果被包含的頁面是JSP,則先處理之後再將結果包含,而如果包含的是非*.jsp文件,則只是把文件內容靜態包含進來,功能與@include類似
三、taglib指令
<%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %>
<% @ taglib %>指令聲明此JSP文件使用了自定義的標簽,同時引用標簽庫,也指定了他們的標簽的前綴
JSP學習(二)JSP指令