一、JSP指令元素简介
JSP指令元素(Directive Elements)是为JSP引擎而设计的,它们并不直接产生任何可见输出,而只是告诉引擎如何处理JSP页面中的其余部分。
在JSP 2.0规范的定义了三个指令:
①page指令
② include指令
③ taglib指令JSP指令的基本语法格式:<%@ 指令 属性名1="值1" 属性名2="值2" ...属性名n="值n"%>
例,用户常在每个JSP页头加上一个指定页面语言和编码方式的指令。
1 <%@ page language="java" contentType="text/html;charset=gb2312"%>
如果一个指令有多个属性,这多个属性可以写在一个指令中,也可以分开写。
1 <%@ page contentType="text/html;charset=gb2312"%> 2 <%@ page import="java.util.Date"%>
二、page指令
page指令用于定义JSP页面的各种属性,无论page指令出现在JSP页面中的什么地方,它作用的都是整个JSP页面,为了保持程序的可读性和遵循良好的编程习惯,page指令最好是放在整个JSP页面的起始位置。例如:
JSP 2.0规范中定义的page指令的完整语法:
<%@ page 2 [ language="java" ] 3 [ extends="package.class" ] 4 [ import="{package.class | package.*}, ..." ] 5 [ session="true | false" ] 6 [ buffer="none | 8kb | sizekb" ] 7 [ autoFlush="true | false" ] 8 [ isThreadSafe="true | false" ] 9 [ info="text" ] 10 [ errorPage="relative_url" ] 11 [ isErrorPage="true | false" ] 12 [ contentType="mimeType [ ;charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ] 13 [ pageEncoding="characterSet | ISO-8859-1" ] 14 [ isELIgnored="true | false" ] 15 %>
2.1、page指令的import属性
在Jsp页面中,Jsp引擎会自动导入下面的包
- java.lang.*
- javax.servlet.*
- javax.servlet.jsp.*
- javax.servlet.http.*
# 可以在一条page指令的import属性中引入多个类或包,其中的每个包或类之间使用逗号(,)分隔。例如:
1 <%@ page import="java.util.*,java.io.*,java.sql.*"%>
# 上面的语句也可以改写为使用多条page指令的import属性来分别引入各个包或类,例如:
1 <%@ page import="java.util.Date"%> 2 <%@ page import="java.io.*" %> 3 <%@ page import="java.sql.*" %>
2.2、page指令的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文件中设置的错误处理将不对该页面起作用。
2.3、使用errorPage属性指明出错后跳转的错误页面
比如Test.jsp页面有如下的代码:
1 <%@ page language="java" import="java.util.*" errorPage="/ErrorPage/error.jsp" pageEncoding="UTF-8"%> 2 <html> 3 <head> 4 <title>测试page指令的errorPage属性</title> 5 </head> 6 <body> 7 <% 8 //这行代码肯定会出错,因为除数是0,一运行就会抛出异常 9 int x = 1/0; 10 %> 11 </body> 12 </html>
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <html> 3 <head> 4 <title>错误信息友好提示页面</title> 5 </head> 6 <body> 7 对不起,出错了,请联系管理员解决! 8 </body> 9 </html>
运行结果如下:
2.4、在web.xml中使用<error-page>标签为整个web应用设置错误处理页面
例如:使用<error-page>标签配置针对404错误的处理页面
web.xml的代码下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 7 <display-name></display-name> 8 <welcome-file-list> 9 <welcome-file>index.jsp</welcome-file> 10 </welcome-file-list> 11 12 <!-- 针对404错误的处理页面 --> 13 <error-page> 14 <error-code>404</error-code> 15 <location>/ErrorPage/404Error.jsp</location> 16 </error-page> 17 </web-app>
404Error.jsp代码如下:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <html> 3 <head> 4 <title>404错误友好提示页面</title> 5 <!-- 3秒钟后自动跳转回首页 --> 6 <meta http-equiv="refresh" content="3;url=${pageContext.request.contextPath}/index.jsp"> 7 </head> 8 <body> 9 <img alt="对不起,你要访问的页面没有找到,请联系管理员处理!" 10 src="${pageContext.request.contextPath}/img/404Error.png"/><br/> 11 3秒钟后自动跳转回首页,如果没有跳转,请点击<a href="${pageContext.request.contextPath}/index.jsp">这里</a> 12 </body> 13 </html>
当访问一个不存在的web资源时,就会跳转到在web.xml中配置的404错误处理页面404Error.jsp,如下图所示:
2.5、使用page指令的的isErrorPage属性显式声明页面为错误页面
# 如果某一个jsp页面是作为系统的错误处理页面,那么建议将page指令的isErrorPage属性(默认为false)设置为"true"来显式声明这个Jsp页面是一个错误处理页面。
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isErrorPage="true"%> 2 <html> 3 <head> 4 <title>错误信息友好提示页面</title> 5 </head> 6 7 <body> 8 对不起,出错了,请联系管理员解决! 9 </body> 10 </html>
# 将error.jsp页面显式声明为错误处理页面后,有什么好处呢,好处就是Jsp引擎在将jsp页面翻译成Servlet的时候,在Servlet的 _jspService方法中会声明一个exception对象,然后将运行jsp出错的异常信息存储到exception对象中,如下所示:
# 由于Servlet的_jspService方法中声明了exception对象,那么就可以在error.jsp页面中使用exception对象,这样就可以在Jsp页面中拿到出错的异常信息了,如下:
# 如果没有设置isErrorPage="true",那么在jsp页面中是无法使用exception对象的,因为在Servlet的_jspService方法中不会声明一个exception对象,如下所示:
# JSP有9大内置对象,而一般情况下exception对象在Jsp页面中是获取不到的,只有设置page指令的isErrorPage属性为"true"来显式声明Jsp页面是一个错误处理页面之后才能够在Jsp页面中使用exception对象。
2.6、session="true|false"
# 设定客户是否需要HTTP Session ,如果为true,那么session是有用的,如果为false,那么用户就不能使用session对象,以及定义scope=session的<jsp::useBean>元素,默认值为true。例如: <%@page session="false"%> <%=session.getId() %> 由于session被设置为false,无法使用session对象,因此该代码会产生异常。
2.7、 isThreadSafe="true|false"
# 设置JSP文件是否能多线程使用,默认值是true。也就是说,JSP能够同时处理多个用户的请求,如果设置为false,一个JSP一次只能处理一个请求。
三、include指令
在JSP中对于包含有两种语句形式: ① @include指令 ② <jsp:include>指令
3.1、@include指令
# 语法:<%@ include file="relativeURL"%>,其中的file属性用于指定被引入文件的相对路径。路径以“/”开头,表示代表当前web应用。
# @include可以包含任意的文件,当然,只是把文件的内容包含进来。
# include指令用于引入其它JSP页面,如果使用include指令引入了其它JSP页面,那么JSP引擎将把这两个JSP翻译成一个servlet。所以include指令引入通常也称之为静态引入。所谓静态的是指file属性值不能是一个变量,例如,下面的file属性赋值的方式是不合法的。
<%String url="head.htmlf";%>
<%@ includefile="<%=url%>"%>
也不可以在file所指定的文件后添加任何参数,下面这行代码也是不合法的: <%@ include file="query.jsp?name=browser"%>
# include指令细节注意问题:
①被引入的文件必须遵循JSP语法。
②被引入的文件可以使用任意的扩展名,即使其扩展名是html,JSP引擎也会按照处理jsp页面的方式处理它里面的内容,为了见名知意,JSP规范建议使用.jspf(JSP fragments(片段))作为静态引入文件的扩展名。
③包含文件中不要使用<html></html>、<body></body>标记,因为这会影响原JSP文件中同样的标记。
④由于使用include指令将会涉及到2个JSP页面,并会把2个JSP翻译成一个servlet,所以这2个JSP页面的指令不能冲突(除了pageEncoding和导包除外)。
# include指令使用范例:
新建head.jspf页面和foot.jspf页面,分别作为jsp页面的头部和尾部,存放于WebRoot下的jspfragments文件夹中,代码如下:
head.jspf代码:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <h1 style="color:red;">网页头部</h1>
foot.jspf代码:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <h1 style="color:blue;">网页尾部</h1>
在WebRoot文件夹下创建一个IncludeTagTest.jsp页面,在IncludeTagTest.jsp页面中使用@include指令引入head.jspf页面和foot.jspf页面,代码如下:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4 <head> 5 <title>jsp的Include指令测试</title> 6 </head> 7 8 <body> 9 <%--使用include标签引入引入其它JSP页面--%> 10 <%@include file="/jspfragments/head.jspf" %> 11 <h1>网页主体内容</h1> 12 <%@include file="/jspfragments/foot.jspf" %> 13 </body> 14 </html>运行结果如下:
我们查看一下jsp引擎将IncludeTagTest.jsp翻译成IncludeTagTest_jsp类之后的源代码,找到Tomcat服务器的work\Catalina\localhost\JavaWeb_Jsp_Study_20140603\org\apache\jsp目录下找到IncludeTagTest_jsp.java,如下图所示:
打开IncludeTagTest_jsp.java,里面的代码如下所示:
1 package org.apache.jsp; 2 3 import javax.servlet.*; 4 import javax.servlet.http.*; 5 import javax.servlet.jsp.*; 6 import java.util.*; 7 import java.util.*; 8 import java.util.*; 9 10 public final class IncludeTagTest_jsp extends org.apache.jasper.runtime.HttpJspBase 11 implements org.apache.jasper.runtime.JspSourceDependent { 12 13 private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); 14 15 private static java.util.List _jspx_dependants; 16 17 static { 18 _jspx_dependants = new java.util.ArrayList(2); 19 _jspx_dependants.add("/jspfragments/head.jspf"); 20 _jspx_dependants.add("/jspfragments/foot.jspf"); 21 } 22 23 private javax.el.ExpressionFactory _el_expressionfactory; 24 private org.apache.AnnotationProcessor _jsp_annotationprocessor; 25 26 public Object getDependants() { 27 return _jspx_dependants; 28 } 29 30 public void _jspInit() { 31 _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); 32 _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName()); 33 } 34 35 public void _jspDestroy() { 36 } 37 38 public void _jspService(HttpServletRequest request, HttpServletResponse response) 39 throws java.io.IOException, ServletException { 40 41 PageContext pageContext = null; 42 HttpSession session = null; 43 ServletContext application = null; 44 ServletConfig config = null; 45 JspWriter out = null; 46 Object page = this; 47 JspWriter _jspx_out = null; 48 PageContext _jspx_page_context = null; 49 50 51 try { 52 response.setContentType("text/html;charset=UTF-8"); 53 pageContext = _jspxFactory.getPageContext(this, request, response, 54 null, true, 8192, true); 55 _jspx_page_context = pageContext; 56 application = pageContext.getServletContext(); 57 config = pageContext.getServletConfig(); 58 session = pageContext.getSession(); 59 out = pageContext.getOut(); 60 _jspx_out = out; 61 62 out.write("\r\n"); 63 out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n"); 64 out.write("<html>\r\n"); 65 out.write(" <head>\r\n"); 66 out.write(" \r\n"); 67 out.write(" <title>jsp的Include指令测试</title>\r\n"); 68 out.write(" \r\n"); 69 out.write(" </head>\r\n"); 70 out.write(" \r\n"); 71 out.write(" <body>\r\n"); 72 out.write(" "); 73 out.write("\r\n"); 74 out.write("<h1 style=\"color:red;\">网页头部</h1>\r\n"); 75 out.write("\r\n"); 76 out.write(" <h1>网页主体内容</h1>\r\n"); 77 out.write(" "); 78 out.write("\r\n"); 79 out.write("<h1 style=\"color:blue;\">网页尾部</h1>\r\n"); 80 out.write("\r\n"); 81 out.write(" </body>\r\n"); 82 out.write("</html>\r\n"); 83 } catch (Throwable t) { 84 if (!(t instanceof SkipPageException)){ 85 out = _jspx_out; 86 if (out != null && out.getBufferSize() != 0) 87 try { out.clearBuffer(); } catch (java.io.IOException e) {} 88 if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); 89 } 90 } finally { 91 _jspxFactory.releasePageContext(_jspx_page_context); 92 } 93 } 94 }可以看到,head.jspf和foot.jspf页面的内容都使用out.write输出到浏览器显示了。
@include指令总结:使用@include可以包含任意的内容,文件的后缀是什么都无所谓。这种把别的文件内容包含到自身页面的@include语句就叫作静态包含,作用只是把别的页面内容包含进来,属于静态包含。
3.2、jsp:include指令
# jsp:include指令为动态包含,如果被包含的页面是JSP,则先处理,之后再将结果包含,而如果包含的是非*.jsp文件,则只是把文件内容静态包含进来,功能与@include类似。后面再具体介绍。
四、taglib指令(了解就ok了)
# taglib指令用来定义一个标签库及其自定义标签的前缀。其语法格式如下:
<%@ tagliburi="tagLibraryURI"prefix="tagPrefix" %>
属性uri(统一资源标识符)用来唯一的确定标签库的路径,并告诉JSP引擎在编译JSP程序时如何处理指定标签库的标签,属性prefix定义了一个只是使用此标签库的前缀。例如:
<%@taglib uri="http://www.jspcentral.com/tags"prefix="public" %>
<public:loop>
...
</public:loop>
在上面的代码中,uri="http://www.jspcentral.com/tags"说明了使用的标签库所在的路径,<public:loop>说明了要使用public标签库额loop标签,如果这里不写public,是不合法的。定义标签时,不能使用jsp、jspx、java、javax、servlet、sun、sunw作为前缀,这些前缀是JSP保留的,在使用自定义标签前必须使用<%@ taglib%>指令,并且可以在一个页面中多次使用,但前缀只能使用一次。