Declaring functions in JSP?

JspFunction

Jsp Problem Overview


I come from PHP world, where declaring a function in the middle of a php page is pretty simple. I tried to do the same in 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;
}

I get the following error:

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

Jsp Solutions


Solution 1 - Jsp

You need to enclose that in <%! %> as follows:

<%!

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

%>

You can then invoke the function within scriptlets or expressions:

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

or

<%= getQuarter(17) %>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan HView Question on Stackoverflow
Solution 1 - Jspkarim79View Answer on Stackoverflow