为什么字符串数组在 JSP 中抛出错误

Why does String Array throw an error in JSP

为什么JSP 无法编译具有以下字符串数组的代码

         <%! String question[];
         question = new String[2];
         question[0] = "What is your name?";
         question[1] = "In what age group are you?";
         %>  

但是如果数组按如下方式初始化,则代码编译 JSP 正确。为什么?

       <%!      
           String question[] = {"What is your name?","In what age group are you?"};     
        %>

数组初始化的正确格式是:

<%!      
  String question[] = new String[]{"What is your name?","In what age group are you?"};     
%>

您的第一个代码段无法编译,因为初始化代码直接放入生成的 class。例如,在 Tomcat 9 中,生成的代码以:

开头
public final class test_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
                 org.apache.jasper.runtime.JspSourceImports {

 String question[];
    question = new String[];
    question[0] = "What is your name?";
    question[1] = "In what age group are you?";

...

这会导致编译错误,因为不允许在方法体之外使用这些语句。

该代码可以在普通的 scriptlet 中运行,即在 <%%> 中,因为该代码将被插入到 render 方法中。

JSP 声明只需要包含带有内联初始化的声明。它不能包含内存分配步骤。内存分配需要在 scriptlet 块中完成。一旦代码更新如下,JSP 编译并执行 w/o 任何问题。

 <%!
     String q;
     String question [];
  %>

  <%

   question = new String[2];
   question[0] = "What is your name?";
   question[1] = "How old are you?";
   %>