在 JSP 中声明函数?

我来自 PHP 世界,在 PHP 页面的中间声明一个函数非常简单。 我尝试在 JSP 中做同样的事情:

public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;


case 2: quarter = "Spring";
break;


case 3: quarter = "Summer I";
break;


case 4: quarter = "Summer II";
break;


case 5: quarter = "Fall";
break;


default: quarter = "ERROR";
}


return quarter;
}

我得到以下错误:

An error occurred at line: 20 in the jsp file: /headers.jsp
Illegal modifier for the variable getQuarter; only final is permitted return;
152769 次浏览

您需要将其包含在 <% !% > 中,如下所示:

<%!


public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;


case 2: quarter = "Spring";
break;


case 3: quarter = "Summer I";
break;


case 4: quarter = "Summer II";
break;


case 5: quarter = "Fall";
break;


default: quarter = "ERROR";
}


return quarter;
}


%>

然后,您可以在 scriptlet 或表达式中调用该函数:

<%
out.print(getQuarter(4));
%>

或者

<%= getQuarter(17) %>