为什么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?"};
%>
您的第一个代码段没有编译,因为初始化代码被直接放入生成的类中。例如,在Tomcat9中,生成的代码以开头
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中工作,即在<%
和%>
中,因为该代码将插入到呈现方法中。
JSP声明只需要包含带内联初始化的声明。它不能包含内存分配步骤。内存分配需要在scriptlet块中完成。代码更新如下后,JSP在没有任何问题的情况下进行编译和执行。
<%!
String q;
String question [];
%>
<%
question = new String[2];
question[0] = "What is your name?";
question[1] = "How old are you?";
%>