JSP 语法与指令

JSP 语法与指令

1. JSP 表达式

<%= expression %> 计算表达式并输出结果。表达式最后计算是有一个结果返回的。一个变量名是一个表达式,还可以进行符号运算,如 a+b

2. 隐式对象

在 JSP 页面中可以在 Java 脚本里面直接使用 Servlet 中讲过的隐式变量,包括:requestresponseoutsessionapplicationconfigpageContext

3. Java 代码

通过 <% code %> 这样的尖括号符号包裹里面的 Java 代码。

4. JSP 声明

<%! code %> 代码被插入到 Servlet 类(在 service 方法之外)。

5. page 指令

<%@ page 属性="值" %> 作用于 Servlet 引擎的全局性指令。合法的属性如下表:

  • import="package.class"
  • contentType="MIME-Type"
  • isThreadSafe="true|false"
  • session="true|false"
  • buffer="size kb|none"
  • autoflush="true|false"
  • extends="package.class"
  • info="message"
  • errorPage="URL"
  • isErrorPage="true|false"
  • language="java"

6. include 指令

<%@ include file="URL" %> 当 JSP 转换成 Servlet 时,应当包含本地系统上的指定文件。利用 jsp:include 动作可以在请求的时候(而不是 JSP 转换成 Servlet 时)引入文件。

7. JSP 注释

<%-- comment --%> 在 JSP 转换成 Servlet 时被忽略。如果要把注释嵌入结果 HTML 文档,使用普通的 HTML 注释标记 <!-- comment -->

8. jsp:include

<jsp:include page="relative URL" flush="true" /> 当 Servlet 被请求时,引入指定的文件。如果你希望在页面转换的时候包含某个文件,使用 JSP include 指令。

注意:在某些服务器上,被包含文件必须是 HTML 文件或 JSP 文件,具体由服务器决定(通常根据文件扩展名判断)。

9. jsp:useBean

语法:<jsp:useBean 属性=值*/>

10. jsp:setProperty

<jsp:setProperty 属性=值*/> 设置 Bean 的属性。合法的属性包括:

  • name="beanName"
  • property="propertyName|*"
  • param="parameterName"
  • value="val"

11. jsp:getProperty

<jsp:getProperty name="propertyName" value="val"/> 提取并输出 Bean 的属性。

12. jsp:forward

<jsp:forward page="relative URL"/> 把请求转到另外一个页面。

查找 JSP 翻译成 Servlet 后的 Java 代码

在 Eclipse 的工作区 workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\(项目名)\org\apache\jsp 这里。

生成的 Servlet 代码示例

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/8.0.53
 * Generated at: 2018-10-14 03:16:47 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;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class search_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;

  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("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=UTF-8");
      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\n");
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>站内搜索</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body style=\"background-color:red;\">\r\n");
      out.write("    <h3> 你的搜索关键词是: </h3>\r\n");
      out.write("\t");
      out.print(request.getParameter("keyword"));
      out.write("\r\n");
      out.write("\t<h3>2你的搜索关键词是:</h3>\r\n");
      out.write("\t");

        String keyword = request.getParameter("keyword");
        if(keyword!=null){
            out.println(keyword);
        }
        
        //声明方法 我们后面会说
/*      public void ShowMessage()
        {
            out.println("好好学习 天天向上 北盟网校");
        } */
    
      out.write("\r\n");
      out.write("\t<br/>\r\n");
      out.write("\t");
      out.print(keyword+"---来自北盟网校" );
      out.write('\r');
      out.write('\n');
      out.write(' ');
  int age = 100; 
      out.write('\r');
      out.write('\n');
      out.write(' ');
      out.print(age );
      out.write("\r\n");
      out.write("\t<!-- <a href=\"\"></a> -->\r\n");
      out.write("\t");
      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } 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);
    }
  }
}Code language: HTML, XML (xml)

继承关系

Class HttpJspBase
java.lang.Object
    javax.servlet.GenericServlet
        javax.servlet.http.HttpServlet
            org.apache.jasper.runtime.HttpJspBaseCode language: CSS (css)

并且我们发现有几个方法和 Servlet 里面的几个方法很像:

public void _jspInit() {
  }
  public void _jspDestroy() {
  }
  public void _jspService(Code language: JavaScript (javascript)

凡是 JSP 文件里面的 HTML 部分,最后都在 _jspService 方法里面通过 out 输出出来:

out.write("\r\n");
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>站内搜索</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body style=\"background-color:red;\">\r\n");
      out.write("    <h3> 你的搜索关键词是: </h3>\r\n");
      out.write("\t");
      out.print(request.getParameter("keyword"));
      out.write("\r\n");
      out.write("\t<h3>2你的搜索关键词是:</h3>\r\n");
      out.write("\t");Code language: HTML, XML (xml)

如果是 HTML,则使用 out.write 直接输出字符串:

out.write("<html>\r\n");Code language: HTML, XML (xml)

如果是表达式,则直接使用 out.print 输出表达式结果:

out.print(request.getParameter("keyword"));Code language: CSS (css)

如果是代码,则直接把它贴到 _jspService 方法里面了,包括 Java 注释的内容:

out.write("\t");

        String keyword = request.getParameter("keyword");
        if(keyword!=null){
            out.println(keyword);
        }
        
        //声明方法 我们后面会说
           /*  public void ShowMessage()
        {
            out.println("好好学习 天天向上 北盟网校");
        } */
    
      out.write("\r\n");Code language: JavaScript (javascript)

如果是 JSP 的注释,则直接过滤了:

<%-- <a href=""></a> --%>Code language: JavaScript (javascript)

这部分内容在 Servlet 类里面没有出现。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注