JSP 声明标签

原文:https://www.studytonight.com/jsp/jsp-declaration-tag.php

我们知道,在最后,一个 JSP 页面被翻译成 Servlet 类。所以当我们在声明标签内部的 JSP 中声明一个变量或方法时,这意味着声明是在 Servlet 类内部而不是在服务(或任何其他)方法外部进行的。您可以在声明标签中声明静态成员、实例变量和方法。声明标记的语法:

<%! declaration %>

声明标签示例

<html>
    <head>
        <title>My First JSP Page</title>
    </head>
    <%!
        int count = 0;
    %>
    <body>
        Page Count is:  
        <% out.println(++count); %>
    </body>
</html>

在上面的代码中,我们已经使用了声明标签来声明变量count。上面的 JSP 页面变成了这个 Servlet:

public class hello_jsp extends HttpServlet
{
  **int count=0;**
  public void **_jspService**(HttpServletRequest request, HttpServletResponse response) 
                               throws IOException,ServletException
    {
      PrintWriter out = response.getWriter();
      response.setContenType("text/html");
      out.write("<html><body>");

      out.write("Page count is:");
      out.print(++count);
      out.write("</body></html>");
   }
}

在上面的 servlet 中,我们可以看到变量count是在_jspservice()方法之外声明的。如果我们使用 scriptlet 标记声明同一个变量,它将出现在服务方法中,如上一课所示。


何时使用声明标签而不是脚本标签

如果你想在你的 JSP 文件中包含任何方法,那么你必须使用声明标签,因为在 JSP 的翻译阶段,声明标签中的方法和变量变成了实例方法和实例变量,并且也被赋予了默认值。

例如:

<html>
    <head>
        <title>My First JSP Page</title>
    </head>
    <%!
       int *count* = 0;
       int **getCount**() {
           System.out.println( "In getCount() method" );
           return count;
       }
    %>
    <body>
        Page Count is:  
        <% out.println(getCount()); %> 
  </body>
</html>

上述代码将被翻译成以下 servlet:

public class hello_jsp extends HttpServlet
{
  **int count = 0;**
  int **getCount**() {
      System.out.println( "In getCount() method" );
      return count;
  }
  public void **_jspService**(HttpServletRequest request, HttpServletResponse response) 
                               throws IOException,ServletException
    {
      PrintWriter out = response.getWriter();
      response.setContenType("text/html");
      out.write("<html><body>");

      out.write("Page count is:");
      out.print(*getCount()*);
      out.write("</body></html>");
   }
}

然而,我们在 scriptlet 标签中添加的任何内容都在_jspservice()方法中,因此我们不能在 scriptlet 标签中添加任何函数,因为在编译时,它会尝试在服务方法中创建一个函数getCount(),而在 Java 中,方法中的方法是不允许的。