小编典典

在JSP中声明函数?

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;

阅读 332

收藏
2020-06-08

共1个答案

小编典典

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

<%!

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;
}

%>

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

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

要么

<%= getQuarter(17) %>
2020-06-08