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

I'm new to Java EE and 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?

This question is related to java jsp scriptlet

The answer is


You can use JSTL tags together with EL expressions to avoid intermixing Java and HTML code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
    <head>
    </head>
    <body>

        <c:out value="${x + 1}" />
        <c:out value="${param.name}" />
        // and so on

    </body>
</html>

As many answers says, use JSTL or create your own custom tags. Here is a good explanation about creating custom tags.


Sure, replace <%! counter++; %> by an event producer-consumer architecture, where the business layer is notified about the need to increment the counter, it reacts accordingly, and notifies the presenters so that they update the views. A number of database transactions are involved, since in future we will need to know the new and old value of the counter, who has incremented it and with what purpose in mind. Obviously serialization is involved, since the layers are entirely decoupled. You will be able to increment your counter over RMI, IIOP, SOAP. But only HTML is required, which you don't implement, since it is such a mundane case. Your new goal is to reach 250 increments a second on your new shiny E7, 64GB RAM server.

I have more than 20 years in programming, most of the projects fail before the sextet: Reusability Replaceability OO-ability Debuggability Testability Maintainability is even needed. Other projects, run by people who only cared about functionality, were extremely successful. Also, stiff object structure, implemented too early in the project, makes the code unable to be adapted to the drastic changes in the specifications (aka agile).

So I consider as procrastination the activity of defining "layers" or redundant data structures either early in the project or when not specifically required.  


In order to avoid Java code in JSP files, Java now provides tag libraries, like JSTL.

Also, Java has come up with JSF into which you can write all programming structures in the form of tags.


  1. Make your values and parameters inside your servlet classes
  2. Fetch those values and parameters within your JSP using JSTL/Taglib

The good thing about this approach is that your code is also HTML like code!


How can I avoid Java code in JSP files?

You can use tab library tags like JSTL in addition to Expression Language (EL). But EL does not work well with JSP. So it's is probably better to drop JSP completely and use Facelets.

Facelets is the first non JSP page declaration language designed for JSF (Java Server Faces) which provided a simpler and more powerful programming model to JSF developers as compare to JSP. It resolves different issues occurs in JSP for web applications development.

Enter image description here

Source


No matter how much you try to avoid, when you work with other developers, some of them will still prefer scriptlet and then insert the evil code into the project. Therefore, setting up the project at the first sign is very important if you really want to reduce the scriptlet code. There are several techniques to get over this (including several frameworks that other mentioned). However, if you prefer the pure JSP way, then use the JSTL tag file. The nice thing about this is you can also set up master pages for your project, so the other pages can inherit the master pages

Create a master page called base.tag under your WEB-INF/tags with the following content

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>

<%@attribute name="title" fragment="true" %>

<html>
  <head>
    <title>  
       <jsp:invoke fragment="title"></jsp:invoke>
    </title>

  </head>
  <body>
    <div id="page-header">
       ....
    </div>
    <div id="page-body">
      <jsp:doBody/>
    </div>
    <div id="page-footer">
      .....
    </div>
  </body>
</html>

On this mater page, I created a fragment called "title", so that in the child page, I could insert more codes into this place of the master page. Also, the tag <jsp:doBody/> will be replaced by the content of the child page

Create child page (child.jsp) in your WebContent folder:

<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:base>
    <jsp:attribute name="title"> 
        <bean:message key="hello.world" />
    </jsp:attribute>

    <jsp:body>
    [Put your content of the child here]
    </jsp:body>   
</t:base>

<t:base> is used to specify the master page you want to use (which is base.tag at this moment). All the content inside the tag <jsp:body> here will replace the <jsp:doBody/> on your master page. Your child page can also include any tag lib and you can use it normally like the other mentioned. However, if you use any scriptlet code here (<%= request.getParameter("name") %> ...) and try to run this page, you will get a JasperException because Scripting elements ( &lt;%!, &lt;jsp:declaration, &lt;%=, &lt;jsp:expression, &lt;%, &lt;jsp:scriptlet ) are disallowed here. Therefore, there is no way other people can include the evil code into the jsp file

Calling this page from your controller:

You can easily call the child.jsp file from your controller. This also works nice with the struts framework


As a Safeguard: Disable Scriptlets For Good

As another question is discussing, you can and always should disable scriptlets in your web.xml web application descriptor.

I would always do that in order to prevent any developer adding scriptlets, especially in bigger companies where you will lose overview sooner or later. The web.xml settings look like this:

<jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
     <scripting-invalid>true</scripting-invalid>
  </jsp-property-group>
</jsp-config>

A lot of the answers here go the "use a framework" route. There's zero wrong with that. However I don't think it really answers your question, because frameworks may or may not use JSPs, nor are they designed in any way with removing java use in JSPs as a primary goal.

The only good answer to your question "how do I avoid using Java in a JSP" is: you can't.

That's what JSPs are for - using Java to render HTML with dynamic data/logic. The follow up question might be, how much java should I use in my JSPs.
Before we answer that question, you should also ponder, "do I need to use JSPs to build web content using Java?" The answer to that last one is, no. There are many alternatives to JSPs for developing web facing applications using Java. Struts for example does not force you to use JSPs - don't get me wrong, you can use them and many implementations do, but you don't absolutely have to. Struts doesn't even force you to use any HTML. A JSP doesn't either, but let's be honest, a JSP producing no HTML is kinda weird. Servlets, famously, allow you to serve any kind of content you like over HTTP dynamically. They are the primary tech behind pretty much everything java web - JSPs are just HTML templates for servlets, really.
So the answer to how much java you should put in a JSP is, "as little as possible". I of course have java in my JSPs, but it consists exclusively of tag library definitions, session and client variables, and beans encapsulating server side objects. The <%%> tags in my HTML are almost exclusively property calls or variable expressions. Rare exceptions include ultra-specific calculations pertaining to a single page and unlikely to ever be reused; bugfixes stemming from page-specific issues only applying to one page; last minute concatenations and arithmetic stemming from unusual requirements limited in scope to a single page; and other similar cases. In a code set of 1.5 million lines, 3000 JSPs and 5000 classes, there are maybe 100 instances of such unique snippets. It would have been quite possible to make these changes in classes or tag library definitions, but it would have been inordinately complex due to the specificity of each case, taken longer to write and debug, and taken more time as a result to get to my users. It's a judgement call. But make no mistake, you cannot write JSPs of any meaning with "no java" nor would you want to. The capability is there for a reason.


If somebody is really against programming in more languages than one, I suggest GWT. Theoretically, you can avoid all the JavaScript and HTML elements, because Google Toolkit transforms all the client and shared code to JavaScript. You won't have problem with them, so you have a webservice without coding in any other languages. You can even use some default CSS from somewhere as it is given by extensions (smartGWT or Vaadin). You don't need to learn dozens of annotations.

Of course, if you want, you can hack yourself into the depths of the code and inject JavaScript and enrich your HTML page, but really you can avoid it if you want, and the result will be good as it was written in any other frameworks. I it's say worth a try, and the basic GWT is well-documented.

And of course many fellow programmers hereby described or recommended several other solutions. GWT is for people who really don't want to deal with the web part or to minimize it.


Just use the JSTL tag and EL expression.


In the MVC architectural pattern, JSPs represent the view layer. Embedding Java code in JSPs is considered a bad practice.

You can use JSTL, freeMarker, and velocity with JSP as a "template engine".

The data provider to those tags depends on frameworks that you are dealing with. Struts 2 and WebWork as an implementation for the MVC pattern uses OGNL "very interesting technique to expose Beans properties to JSP".


Using scriptlets in JSPs is not a good practice.

Instead, you can use:

  1. JSTL tags
  2. EL expressions
  3. Custom Tags- you can define your own tags to use.

Please refer to:

  1. http://docs.oracle.com/javaee/1.4/tutorial/doc/JSTL3.html
  2. EL

By using JSTL tags together with EL expressions, you can avoid this. Put the following things in your JSP page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

Nothing of that is used anymore, my friend. My advice is to decouple the view (CSS, HTML, JavaScript, etc.) from the server.

In my case, I do my systems handling the view with Angular and any data needed is brought from the server using REST services.

Believe me, this will change the way you design.


You raised a good question and although you got good answers, I would suggest that you get rid of JSP. It is outdated technology which eventually will die. Use a modern approach, like template engines. You will have very clear separation of business and presentation layers, and certainly no Java code in templates, so you can generate templates directly from web presentation editing software, in most cases leveraging WYSIWYG.

And certainly stay away of filters and pre and post processing, otherwise you may deal with support/debugging difficulties since you always do not know where the variable gets the value.


JSTL offers tags for conditionals, loops, sets, gets, etc. For example:

<c:if test="${someAttribute == 'something'}">
   ...
</c:if>

JSTL works with request attributes - they are most often set in the request by a Servlet, which forwards to the JSP.


Wicket is also an alternative which completely separates Java from HTML, so a designer and programmer can work together and on different sets of code with little understanding of each other.

Look at Wicket.


Technically, JSP are all converted to Servlets during runtime.

JSP was initially created for the purpose of the decoupling the business logic and the design logic, following the MVC pattern. So JSP is technically all Java code during runtime.

But to answer the question, tag libraries are usually used for applying logic (removing Java code) to JSP pages.


If you simply want to avoid the drawbacks of Java coding in JSP you can do so even with scriplets. Just follow some discipline to have minimal Java in JSP and almost no calculation and logic in the JSP page.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% // Instantiate a JSP controller
MyController clr = new MyController(request, response);

// Process action, if any
clr.process(request);

// Process page forwarding, if necessary

// Do all variable assignment here
String showMe = clr.getShowMe();%>

<html>
    <head>
    </head>
    <body>
        <form name="frm1">
            <p><%= showMe %>
            <p><% for(String str : clr.listOfStrings()) { %>
            <p><%= str %><% } %>

            // And so on   
        </form>
    </body>
</html>

JSP 2.0 has a feature called "Tag Files", and you can write tags without external Java code and tld. You need to create a .tag file and put it in WEB-INF\tags. You can even create a directory structure to package your tags.

For example:

/WEB-INF/tags/html/label.tag

<%@tag description="Rensders a label with required css class" pageEncoding="UTF-8"%>
<%@attribute name="name" required="true" description="The label"%>

<label class="control-label control-default"  id="${name}Label">${name}</label>

Use it like

<%@ taglib prefix="h" tagdir="/WEB-INF/tags/html"%>
<h:label  name="customer name" />

Also, you can read the tag body easily:

/WEB-INF/tags/html/bold.tag
<%@tag description="Bold tag" pageEncoding="UTF-8"%>
<b>
  <jsp:doBody/>
</b>

Use it:

<%@ taglib prefix="h" tagdir="/WEB-INF/tags/bold"%>
<h:bold>Make me bold</h:bold>

The samples are very simple, but you can do lots of complicated tasks here. Please consider you can use other tags (for example: JSTL which has controlling tags like if/forEcah/chosen text manipulation like format/contains/uppercase or even SQL tags select/update), pass all kind parameters, for example Hashmap, access session, request, ... in your tag file too.

Tag File are so easy developed as you did not need to restart the server when changing them, like JSP files. This makes them easy for development.

Even if you use a framework like Struts 2, which have lots of good tags, you may find that having your own tags can reduce your code a lot. You can pass your tag parameters to struts and this way customize your framework tag.

You can use tags not only to avoid Java, but also minimize your HTML codes. I myself try to review HTML code and build tags a lot as soon as I see code duplicates start in my pages.

(Even if you end up using Java in your JSP code, which I hope not, you can encapsulate that code in a tag.)


Learn to customize and write your own tags using JSTL

Note that EL is EviL (runtime exceptions and refactoring).

Wicket may be evil too (performance and toilsome for small applications or simple view tier).

Example from java2s

This must be added to the web application's web.xml

<taglib>
    <taglib-uri>/java2s</taglib-uri>
    <taglib-location>/WEB-INF/java2s.tld</taglib-location>
</taglib>

Create file java2s.tld in the /WEB-INF/

<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
   "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<!-- A tab library descriptor -->
<taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>Java2s Simple Tags</short-name>

    <!-- This tag manipulates its body content by converting it to upper case
    -->
    <tag>
        <name>bodyContentTag</name>
        <tag-class>com.java2s.BodyContentTag</tag-class>
        <body-content>JSP</body-content>
        <attribute>
          <name>howMany</name>
        </attribute>
    </tag>
</taglib>

Compile the following code into WEB-INF\classes\com\java2s

package com.java2s;

import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class BodyContentTag extends BodyTagSupport{
    private int iterations, howMany;

    public void setHowMany(int i){
        this.howMany = i;
    }

    public void setBodyContent(BodyContent bc){
        super.setBodyContent(bc);
        System.out.println("BodyContent = '" + bc.getString() + "'");
    }

    public int doAfterBody(){
        try{
            BodyContent bodyContent = super.getBodyContent();
            String bodyString  = bodyContent.getString();
            JspWriter out = bodyContent.getEnclosingWriter();

            if ( iterations % 2 == 0 )
                out.print(bodyString.toLowerCase());
            else
                out.print(bodyString.toUpperCase());

            iterations++;
            bodyContent.clear(); // empty buffer for next evaluation
        }
        catch (IOException e) {
            System.out.println("Error in BodyContentTag.doAfterBody()" + e.getMessage());
            e.printStackTrace();
        } // End of catch

        int retValue = SKIP_BODY;

        if ( iterations < howMany )
            retValue = EVAL_BODY_AGAIN;

        return retValue;
    }
}

Start the server and load the bodyContent.jsp file in the browser:

<%@ taglib uri="/java2s" prefix="java2s" %>
<html>
    <head>
        <title>A custom tag: body content</title>
    </head>
    <body>
        This page uses a custom tag manipulates its body content.Here is its output:
        <ol>
            <java2s:bodyContentTag howMany="3">
            <li>java2s.com</li>
            </java2s:bodyContentTag>
        </ol>
    </body>
</html>

If we use the following things in a Java web application, Java code can be eliminated from the foreground of the JSP file.

  1. Use the MVC architecture for a web application

  2. Use JSP Tags

a. Standard Tags

b. Custom Tags

  1. Expression Language

Using Scriptlets is a very old way and not recommended. If you want directly output something in your JSP pages, just use Expression Language (EL) along with JSTL.

There are also other options, such as using a templating engine such as Velocity, Freemarker, Thymeleaf, etc. But using plain JSP with EL and JSTL serves my purpose most of the time and it also seems the simplest for a beginner.

Also, take note that it is not a best practice to do business logic in the view layer. You should perform your business logic in the service layer, and pass the output result to your views through a controller.


Use JSTL tag libraries in JSP. That will work perfectly.


There are also component-based frameworks, such as Wicket, that generate a lot of the HTML for you.

The tags that end up in the HTML are extremely basic and there is virtually no logic that gets mixed in. The result is almost empty-like HTML pages with typical HTML elements. The downside is that there are a lot of components in the Wicket API to learn and some things can be difficult to achieve under those constraints.


A neat idea from the Python world is Template attribute languages; TAL was introduced by Zope (therefore a.k.a. "Zope Page Templates", ZPT) and is a standard, with implementations in PHP, XSLT and Java as well (I have used the Python/Zope and PHP incarnations). In this class of templating languages, one of the above examples could look like this:

<table>
    <tr tal:repeat="product products">
        <td tal:content="product/name">Example product</td>
        <td tal:content="product/description">A nice description</td>
        <td tal:content="product/price">1.23</td>
    </tr>
</table>

The code looks like ordinary HTML (or XHTML) plus some special attributes in an XML namespace; it can be viewed with a browser and safely be tweaked by a designer.

There is support for macros and for internationalisation and localisation as well:

<h1 i18n:translate="">Our special offers</h1>
<table>
    <tr tal:repeat="product products">
        <td tal:content="product/name"
            i18n:translate="">Example product</td>
        <td tal:content="product/description"
            i18n:translate="">A nice description</td>
        <td tal:content="product/price">1.23</td>
    </tr>
</table>

If translations of the content are available, they are used.

I don't know very much about the Java implementation, though.


Experience has shown that JSP's have some shortcomings, one of them being hard to avoid mixing markup with actual code.

If you can, then consider using a specialized technology for what you need to do. In Java EE 6 there is JSF 2.0, which provides a lot of nice features including gluing Java beans together with JSF pages through the #{bean.method(argument)} approach.


Use a Backbone.js or AngularJS-like JavaScript framework for UI design and fetch the data using a REST API. This will remove the Java dependency from the UI completely.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to scriptlet

Using if-else in JSP How do I pass JavaScript values to Scriptlet in JSP? I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error How can I avoid Java code in JSP files, using JSP 2?