73

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;
Arshad Ali
  • 3,082
  • 12
  • 56
  • 99
Nathan H
  • 48,033
  • 60
  • 165
  • 247

1 Answers1

134

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) %>
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 11
    You can, but you shouldn't. – Adam Jaskiewicz May 05 '09 at 21:25
  • 17
    Adam, why shouldn't you? Please explain, please. – ericso Jul 19 '12 at 23:37
  • 11
    just in case anyone like me wanders what is the difference between <%! %> and <% %> there is a good explanation here: http://stackoverflow.com/questions/5508753/difference-between-and – epeleg Feb 26 '13 at 07:58
  • @ericso You shouldn't because doing it this way is hard to debug, etc.; see http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files?rq=1 for more info – auspicious99 Apr 23 '15 at 01:50
  • Declare public static functions in the proper class, and if you need functions because of hierarchy/modularity or structural reasons then put it in a separate JSP, and include that. In the latter case, parameters can be passed on with `request.setAttribute(String, Object)` and `request.getAttribute(String, Object)`. If you still think that you need to declare functions in JSP, then think again why you are using JSP in the first place. – Yeti Nov 04 '17 at 17:07