javaweb之jsp指令
1.JSP指令簡介
JSP指令是為JSP引擎設計的,它們並不直接產生任何可見輸出,而只是告訴引擎如何處理JSP頁面中的其余部分。
在JSP 2.0規範中共定義了三個指令:page指令,Include指令,taglib指令。
JSP指令的基本語法格式:<%@ 指令 屬性名="值" %>
例如:
<%@ page contentType="text/html;charset=gb2312"%>
如果一個指令有多個屬性,這多個屬性可以寫在一個指令中,也可以分開寫。
例如:
<%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.util.Date"%>
也可以寫作:
<%@ page contentType="text/html;charset=gb2312" import="java.util.Date"%>
2.page指令
page指令用於定義JSP頁面的各種屬性,無論page指令出現在JSP頁面中的什麽地方,它作用的都是整個JSP頁面,為了保持程序的可讀性和遵循良好的編程習慣,page指令最好是放在整個JSP頁面的起始位置。
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" ] %>
2.1 import屬性
在jsp頁面中,jsp引擎會自動導入下面的包和類:
java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*
可以在一條page指令引入多個類和包,其中的每個包和類之間使用逗號分隔開,例如,
<%@ page import="java.util.Date,java.sql.*,java.io.*"%>
2.2 errorPage屬性
- errorPage屬性的設置值必須使用相對路徑,如果以“/”開頭,表示相對於當前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>
- 如果設置了某個JSP頁面的errorPage屬性,那麽在web.xml文件中設置的錯誤處理將不對該頁面起作用。
jsperrorPage的相對路徑,“/”表示當前web應用程序的根目錄(WebRoot),“./”代表當前目錄(即當前文件所在的目錄),“../”代表當前文件所在目錄的上一級目錄。
例如有以下的工程目錄結構:
testA.jsp中page指令的errorPage路徑為:
<%@ page import="java.util.Date" errorPage="/jspTest/error.jsp"%>
即路徑"/jspTest/error.jsp"為“WebRoot/jspTest/error.jsp”。
使用errorPage屬性可以指明出錯後跳轉的錯誤頁面,比如如下的testA.jsp代碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="java.util.Date" errorPage="/jspTest/error.jsp"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘testA.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% int i=2/0; %> </body> </html>
int i=2/0,顯然出錯,第二行page指令的errorPage屬性<%@ page import="java.util.Date" errorPage="/jspTest/error.jsp"%>指明出錯後跳轉到error.jsp文件,error.jsp的內容為:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="java.io.PrintWriter" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘error.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% PrintWriter outs=response.getWriter(); outs.write("出錯啦!"); %> </body> </html>
運行結果如下:
2.3 在web.xml中使用<error-page>標簽為整個web應用設置錯誤處理頁面
例如,使用<error-page>標簽配置針對404錯誤的處理頁面,在web.xml中的配置如下:
<?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> <!-- 針對404錯誤的處理頁面 --> <error-page> <error-code>404</error-code> <location>/jspTest/error.jsp</location> </error-page> </web-app>
要跳轉的error.jsp的代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <title>404錯誤友好提示頁面</title> <!-- 3秒鐘後自動跳轉回首頁 --> <meta http-equiv="refresh" content="3;url=${pageContext.request.contextPath}/WEB-INF/index.jsp"> </head> <body> <p>404錯誤</p> <br/> 3秒鐘後自動跳轉回首頁,如果沒有跳轉,請點擊<a href="${pageContext.request.contextPath}/index.jsp">這裏</a> </body> </html>
當訪問一個不存在的web資源時,就會跳轉到在web.xml中配置的404錯誤處理頁面error.jsp,
2.4 使用isErrorPage屬性顯示聲明頁面為錯誤
如果某一個jsp頁面是作為系統的錯誤處理頁面,那麽建議將page指令的isErrorPage屬性(默認為false)設置為“true”來顯示聲明這個jsp頁面是一個錯誤處理頁面。將error.jsp頁面顯式聲明為錯誤處理頁面後,好處就是Jsp引擎在將jsp頁面翻譯成Servlet的時候,在Servlet的 _jspService方法中會聲明一個exception對象,然後將運行jsp出錯的異常信息存儲到exception對象中,由於Servlet的_jspService方法中聲明了exception對象,那麽就可以在error.jsp頁面中使用exception對象,這樣就可以在Jsp頁面中拿到出錯的異常信息了。如果沒有設置isErrorPage="true",那麽在jsp頁面中是無法使用exception對象的。
若指定isErrorPage=“true”,並使用exception的方法了,一般不建議能夠直接訪問該頁面,而只作為請求轉發的方式訪問。
Jsp有9大內置對象,而一般情況下exception對象在Jsp頁面中是獲取不到的,只有設置page指令isErrorPage屬性為“true”來顯示聲明一個jsp頁面是一個錯誤處理頁面之後才能夠在jsp頁面中使用exception對象。
3.include指令
在JSP中對於包含有兩種語句形式:@include指令和<jsp:include>指令
3.1 @include指令
include指令用於引入其它JSP頁面,如果使用include指令引入了其它JSP頁面,那麽JSP引擎將把這兩個JSP翻譯成一個servlet。所以include指令引入通常也稱之為靜態引入。
語法:<%@ include file="relativeURL"%>,其中的file屬性用於指定被引入文件的路徑。路徑以“/”開頭,表示代表當前web應用。
例如:
includeTest1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path1 = request.getContextPath(); String basePath1 = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath1%>"> <title>My JSP ‘includeTest.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h2>"includeTest1.jsp‘s content"</h2> <%@ include file="includeTest2.jsp" %> </body> </html>
includeTest2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘includeTest2.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h2>"includeTest2.jsp‘s content"</h2> </body> </html>
includeTest1.jsp使用<%@ include file="includeTest2.jsp" %>將includeTest2.jsp內容包含進去,由於include會涉及到兩個jsp頁面,並會把兩個jsp翻譯成一個servlet,所以這兩個jsp的指令(除pageEncoding和import之外)以及定義的變量名不能重復。尤其註意新建jsp文件原有的代碼中的String path和String basePath,要註意修改其中的一個jsp文件的變量名,否則會出現變量名重復定義的錯誤。如下就是include includeTest2.jsp之後轉換成的includeTest1_jsp類的源代碼。
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/8.5.9 * Generated at: 2018-10-20 13:08:44 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.jspTest; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import java.util.*; import java.util.*; public final class includeTest1_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent, org.apache.jasper.runtime.JspSourceImports { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; static { _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1); _jspx_dependants.put("/jspTest/includeTest2.jsp", Long.valueOf(1540040843018L)); } private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("java.util"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final java.lang.String _jspx_method = request.getMethod(); if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD"); return; } final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=ISO-8859-1"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write(‘\r‘); out.write(‘\n‘); String path1 = request.getContextPath(); String basePath1 = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/"; out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n"); out.write("<html>\r\n"); out.write(" <head>\r\n"); out.write(" <base href=\""); out.print(basePath1); out.write("\">\r\n"); out.write(" \r\n"); out.write(" <title>My JSP ‘includeTest.jsp‘ starting page</title>\r\n"); out.write(" \r\n"); out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n"); out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n"); out.write("\t<meta http-equiv=\"expires\" content=\"0\"> \r\n"); out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n"); out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n"); out.write("\t<!--\r\n"); out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n"); out.write("\t-->\r\n"); out.write("\r\n"); out.write(" <script>\"undefined\"==typeof CODE_LIVE&&(!function(e){var t={nonSecure:\"51550\",secure:\"51555\"},c={nonSecure:\"http://\",secure:\"https://\"},r={nonSecure:\"127.0.0.1\",secure:\"gapdebug.local.genuitec.com\"},n=\"https:\"===window.location.protocol?\"secure\":\"nonSecure\";script=e.createElement(\"script\"),script.type=\"text/javascript\",script.async=!0,script.src=c[n]+r[n]+\":\"+t[n]+\"/codelive-assets/bundle.js\",e.getElementsByTagName(\"head\")[0].appendChild(script)}(document),CODE_LIVE=!0);</script></head>\r\n"); out.write(" \r\n"); out.write(" <body data-genuitec-lp-enabled=\"false\" data-genuitec-file-id=\"wc1-8\" data-genuitec-path=\"/MyWebProject/WebRoot/jspTest/includeTest1.jsp\">\r\n"); out.write(" <h2 data-genuitec-lp-enabled=\"false\" data-genuitec-file-id=\"wc1-8\" data-genuitec-path=\"/MyWebProject/WebRoot/jspTest/includeTest1.jsp\">\"includeTest1.jsp‘s content\"</h2>\r\n"); out.write(" "); out.write(‘\r‘); out.write(‘\n‘); String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n"); out.write("<html>\r\n"); out.write(" <head>\r\n"); out.write(" <base href=\""); out.print(basePath); out.write("\">\r\n"); out.write(" \r\n"); out.write(" <title>My JSP ‘includeTest2.jsp‘ starting page</title>\r\n"); out.write(" \r\n"); out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n"); out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n"); out.write("\t<meta http-equiv=\"expires\" content=\"0\"> \r\n"); out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n"); out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n"); out.write("\t<!--\r\n"); out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n"); out.write("\t-->\r\n"); out.write("\r\n"); out.write(" <script>\"undefined\"==typeof CODE_LIVE&&(!function(e){var t={nonSecure:\"51550\",secure:\"51555\"},c={nonSecure:\"http://\",secure:\"https://\"},r={nonSecure:\"127.0.0.1\",secure:\"gapdebug.local.genuitec.com\"},n=\"https:\"===window.location.protocol?\"secure\":\"nonSecure\";script=e.createElement(\"script\"),script.type=\"text/javascript\",script.async=!0,script.src=c[n]+r[n]+\":\"+t[n]+\"/codelive-assets/bundle.js\",e.getElementsByTagName(\"head\")[0].appendChild(script)}(document),CODE_LIVE=!0);</script></head>\r\n"); out.write(" \r\n"); out.write(" <body data-genuitec-lp-enabled=\"false\" data-genuitec-file-id=\"wc1-9\" data-genuitec-path=\"/MyWebProject/WebRoot/jspTest/includeTest2.jsp\">\r\n"); out.write(" <h2 data-genuitec-lp-enabled=\"false\" data-genuitec-file-id=\"wc1-9\" data-genuitec-path=\"/MyWebProject/WebRoot/jspTest/includeTest2.jsp\">\"includeTest2.jsp‘s content\"</h2>\r\n"); out.write(" </body>\r\n"); out.write("</html>\r\n"); out.write("\r\n"); out.write(" </body>\r\n"); out.write("</html>\r\n"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
可以看到,includeTest1.jsp和includeTest2.jsp頁面的內容都使用out.write輸出到瀏覽器了。運行includeTest1.jsp後,顯示如下的結果:
使用@include可以包含任意的內容,文件的後綴是什麽都無所謂。這種把別的文件內容包含到自身頁面的@include語句就叫作靜態包含,作用只是把別的頁面內容包含進來,屬於靜態包含。
3.2 jsp:include指令
接jsp標簽。
javaweb之jsp指令