javajspscriptlet

How can I avoid Java code in JSP files, using JSP 2?


I know that something like the following three lines

<%= x+1 %>
<%= request.getParameter("name") %>
<%! counter++; %>

is an old school way of coding and in JSP version 2 there exists a method to avoid Java code in JSP files. What are the alternative JSP 2 lines, and what is this technique called?


Solution

  • The use of scriptlets (those <% %> things) in JSP is indeed highly discouraged since the birth of taglibs (like JSTL) and EL (Expression Language, those ${} things) way back in 2001.

    The major disadvantages of scriptlets are:

    1. Reusability: you can't reuse scriptlets.
    2. Replaceability: you can't make scriptlets abstract.
    3. OO-ability: you can't make use of inheritance/composition.
    4. Debuggability: if scriptlet throws an exception halfway, all you get is a blank page.
    5. Testability: scriptlets are not unit-testable.
    6. Maintainability: per saldo more time is needed to maintain mingled/cluttered/duplicated code logic.

    Sun Oracle itself also recommends in the JSP coding conventions to avoid use of scriptlets whenever the same functionality is possible by (tag) classes. Here are several cites of relevance:

    From JSP 1.2 Specification, it is highly recommended that the JSP Standard Tag Library (JSTL) be used in your web application to help reduce the need for JSP scriptlets in your pages. Pages that use JSTL are, in general, easier to read and maintain.

    ...

    Where possible, avoid JSP scriptlets whenever tag libraries provide equivalent functionality. This makes pages easier to read and maintain, helps to separate business logic from presentation logic, and will make your pages easier to evolve into JSP 2.0-style pages (JSP 2.0 Specification supports but de-emphasizes the use of scriptlets).

    ...

    In the spirit of adopting the model-view-controller (MVC) design pattern to reduce coupling between the presentation tier from the business logic, JSP scriptlets should not be used for writing business logic. Rather, JSP scriptlets are used if necessary to transform data (also called "value objects") returned from processing the client's requests into a proper client-ready format. Even then, this would be better done with a front controller servlet or a custom tag.


    How to replace scriptlets entirely depends on the sole purpose of the code/logic. More than often this code is to be placed in a fullworthy Java class:

    See also: