Java code inside JSP page

Java Server pages technology allows us to combine HTML (or some other) output and Java code in a single JSP file. Although mixing Java code with HTML output generally isn’t very good development approach, there are situations when you can’t avoid it. Recently I worked on a project where I had to do some changes on the portion of an old code where Java was heavily used inside JSP pages. Here I’ll list several guidelines that I came up with while working on mentioned project, and that could improve code organization.

There are different ways to include Java code in JSP page: JSP expressions, JSP scriptlets and JSP declarations.

JSP expression is used to insert a value of Java expression, converted to String, into a response returned to the client.

<prompt>
    <audio src="<%=getSoundUrl("welcome.wav")%>"/>
</prompt>

JSP scriptlet is a container for Java code fragment in a JSP page. When a page is translated to a servlet class, scriptlet content is inserted into _jspService() method of the servlet class.

<%
    String userID = request.getParameter("userid");
    String userStatus = getUserStatus(userID);
    String audioFile = "";
    if(userStatus.equals(UserStatus.NEW)) {
        audioFile = "new.wav";
    } else {
        audioFile = "existing.wav";
    }
%>
<prompt>
    <audio src="<%=getSoundUrl(audioFile)%>"/>
</prompt>

JSP declaration is used to declare methods and variables global for a JSP page. On page translation, declared methods and variables become class member declarations in JSP page’s servlet class.

<%!
    private final Logger logger = new Logger(this.getClass());
    private UserService userService = null;
    public void jspInit() {
        userService = new UserService();
    }
    private String getUserStatus(String userID) {
        return userServce.getUserStatus(userID);
    }
%>

Developers usually put all Java code inside JSP scriptlets, but even in the JSP page code can be well organized to improve code readability.

For better understanding, let’s see what happens when a request mapped to a JSP page is processed.

If servlet class for requested JSP page does not exist, web container translates JSP page to the servlet class and compiles it.
If an instance of JSP page’s servlet class does not exist, web container loads the servlet class, instantiates an instance of the servlet class and initializes the servlet instance by invoking jspInit() method.
Finally, web container invokes _jspService() method.

You can customize servlet initialization and finalization processes by overriding jspInit() and jspDestroy() methods. These methods have to be defined as JSP declarations. All one-time activities like resources initialization and reading persistent configuration data should go into jspInit() method since this portion of code will get executed only once, when JSP page’s servlet class is loaded.

Only a code that has to be executed for every request should remain in JSP scriptlets. Amount of the code in scriptlets can also be minimized by organizing the code in methods and isolating them in JSP declarations, so that scriptlet contains only method calls. Since methods and variables defined in JSP declarations act as class members of the JSP page’s servlet class, they are accessible from anywhere within the page.

To conclude, the main goal is to separate the Java code form HTML or other output as much as possible. That way JSP page is better organized and it’s made significantly more readable.