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)来显式声明Jsp页面是一个错误处理页面之后才能够在Jsp页面中使用exception对象。

在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类似

扫描二维码关注公众号,回复: 1598475 查看本文章

三、taglib指令

<%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %>

<% @ taglib %>指令声明此JSP文件使用了自定义的标签,同时引用标签库,也指定了他们的标签的前缀

猜你喜欢

转载自www.cnblogs.com/huangdabing/p/9185577.html