By former

2010-07-05 07:24:06 8 Comments

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. Can someone please tell me the alternative JSP 2 lines, and what this technique is called?


@Yster 2015-12-24 11:47:27

How to 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


@casgage 2017-02-01 02:52:45

I definitely second this response. JSF with or without Facelets. I thought developing in JSP had largely ceased more than 10 years ago. I last wrote JSPs in 2000!

@Alireza Fattahi 2016-04-12 14:55:51

JSP 2.0 has a feature called "Tag Files", 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:


<%@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

<%@tag description="Bold tag" pageEncoding="UTF-8"%>

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 (eg: 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 tag not only to avoid java but also minimize your HTML codes. I myself try to review HTML codes and build tags a lot as soon as see code duplicates start in my pages.

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

@BalusC 2010-07-05 14:19:35

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:

  • If you want to invoke the same Java code on every request, less-or-more regardless of the requested page, e.g. checking if a user is logged in, then implement a filter and write code accordingly in doFilter() method. E.g.:

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (((HttpServletRequest) request).getSession().getAttribute("user") == null) {
            ((HttpServletResponse) response).sendRedirect("login"); // Not logged in, redirect to login page.
        } else {
            chain.doFilter(request, response); // Logged in, just continue request.

    When mapped on an appropriate <url-pattern> covering the JSP pages of interest, then you don't need to copypaste the same piece of code overall JSP pages.

  • If you want to invoke some Java code to preprocess a request, e.g. preloading some list from a database to display in some table, if necessary based on some query parameters, then implement a servlet and write code accordingly in doGet() method. E.g.:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Product> products = productService.list(); // Obtain all products.
            request.setAttribute("products", products); // Store products in request scope.
            request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.
        } catch (SQLException e) {
            throw new ServletException("Retrieving products failed!", e);

    This way dealing with exceptions is easier. The DB is not accessed in the midst of JSP rendering, but far before the JSP is been displayed. You still have the possibility to change the response whenever the DB access throws an exception. In the above example, the default error 500 page will be displayed which you can anyway customize by an <error-page> in web.xml.

  • If you want to invoke some Java code to postprocess a request, e.g. processing a form submit, then implement a servlet and write code accordingly in doPost() method. E.g.:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.find(username, password);
        if (user != null) {
            request.getSession().setAttribute("user", user); // Login user.
            response.sendRedirect("home"); // Redirect to home page.
        } else {
            request.setAttribute("message", "Unknown username/password. Please retry."); // Store error message in request scope.
            request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to JSP page to redisplay login form with error.

    This way dealing with different result page destinations is easier: redisplaying the form with validation errors in case of an error (in this particular example you can redisplay it using ${message} in EL), or just taking to the desired target page in case of success.

  • If you want to invoke some Java code to control the execution plan and/or the destination of the request and the response, then implement a servlet according to the MVC's Front Controller Pattern. E.g.:

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Action action = ActionFactory.getAction(request);
            String view = action.execute(request, response);
            if (view.equals(request.getPathInfo().substring(1)) {
                request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
            } else {
        } catch (Exception e) {
            throw new ServletException("Executing action failed.", e);

    Or just adopt an MVC framework like JSF, Spring MVC, Wicket, etc so that you end up with just a JSP/Facelets page and a JavaBean class without the need for a custom servlet.

  • If you want to invoke some Java code to control the flow inside a JSP page, then you need to grab an (existing) flow control taglib like JSTL core. E.g. displaying List<Product> in a table:

    <%@ taglib uri="" prefix="c" %>
        <c:forEach items="${products}" var="product">

    With XML-style tags which fit nicely among all that HTML, the code is better readable (and thus better maintainable) than a bunch of scriptlets with various opening and closing braces ("Where the heck does this closing brace belong to?"). An easy aid is to configure your web application to throw an exception whenever scriptlets are still been used by adding the following piece to web.xml:


    In Facelets, the successor of JSP, which is part of the Java EE provided MVC framework JSF, it is already not possible to use scriptlets. This way you're automatically forced to do things "the right way".

  • If you want to invoke some Java code to access and display "backend" data inside a JSP page, then you need to use EL (Expression Language), those ${} things. E.g. redisplaying submitted input values:

    <input type="text" name="foo" value="${}" />

    The ${} displays the outcome of request.getParameter("foo").

  • If you want to invoke some utility Java code directly in the JSP page (typically public static methods), then you need to define them as EL functions. There's a standard functions taglib in JSTL, but you can also easily create functions yourself. Here's an example how JSTL fn:escapeXml is useful to prevent XSS attacks.

    <%@ taglib uri="" prefix="fn" %>
    <input type="text" name="foo" value="${fn:escapeXml(}" />

    Note that the XSS sensitivity is in no way specifically related to Java/JSP/JSTL/EL/whatever, this problem needs to be taken into account in every web application you develop. The problem of scriptlets is that it provides no way of builtin preventions, at least not using the standard Java API. JSP's successor Facelets has already implicit HTML escaping, so you don't need to worry about XSS holes in Facelets.

See also:

@svachon 2010-07-06 01:58:28

+1 Great answer. But don't go dogmatic, sometime using scriptlets IS ok, but that should be the exception that proves the rule.

@BalusC 2010-07-06 13:25:32

@svachon: Scriptlets are useful for quick prototyping/testing. As far as I know, there's only one "legitimate" production use of a scriptlet, namely <% response.getWriter().flush(); %> between the </head> and the <body> to improve webpage parsing performance in the webbrowser. But this use is in turn completely negligible when the output buffer size at the server side is low (1~2KB). See also this article.

@svachon 2010-07-06 14:30:22

@BalusC A few times I've been stuck with java classes that didn't follow the getter/setter pattern. IMHO that is a case where a scripltet does the job.

@BalusC 2010-07-06 14:37:44

@svachon: I'd wrap those classes with own javabean classes and use them instead.

@svachon 2010-07-06 16:04:06

@BalusC I agree with you that this is the best practice approach, especially with the question beign "howto avoid".

@Bart van Heukelom 2011-11-02 09:23:45

I assume "4. Debuggability" it not true when using JSP as view technology in a framework like Spring MVC?

@parasietje 2012-02-24 15:04:36

Can you adjust the answer to stress the move to JSF2 or Wicket? It seems the Java EE and Web world is pushing towards this as the correct solution for removing logic from JSP pages.

@BalusC 2012-02-24 15:50:50

@parasietje: I don't want to stress too much. I've at least expanded the answer to attend the usage of a MVC framework a bit more.

@MetroidFan2002 2012-09-07 01:05:46

It was a pretty good answer, but the doGet and doPost parts are misleading. Those methods are for handling specific request (HEAD, GET and POST) methods and aren't for "preprocessing" or "postprocessing" requests!

@BalusC 2012-09-07 01:28:28

@Met: The way I explained is the most clear for starters who don't understand how HTTP works ;) Which is actually also how HTML form based web applications generally work. If you are thinking RESTful, for example, then my explanation on that part makes of course no sense.

@Daniel Kaplan 2013-06-12 07:07:38

Is it a bad idea to use scriplets in custom made .tag files?

@Aerox 2014-03-27 10:42:56

@BalusC Why doesn't make sense in RESTful web app? Could you explain what you mean? Thanks (I'm a starter as you mentioned)

@CubeJockey 2015-08-21 17:40:58

@jpaugh 2016-08-12 00:58:30

@MetroidFan2002 That stumped me too! BalusC, This only makes sense in terms of a post-back flow, which isn't necessarily the most intuitive way to handle or think about forms, and certainly not the first model I learned. I'll grant it as being a common way for beginners to approach JSP / ASP Classic, though.

@Jens Bannmann 2018-05-01 08:40:05

For template logic or visuals, one could also write custom tag handler classes if the standard taglib doesn't suffice. How about adding this to the answer?

@Mehdi 2018-12-01 16:04:09

  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!

@Behrang 2010-07-05 08:45:54

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="" prefix="c" %>
<%@ taglib uri="" prefix="fmt" %>

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


@Sumesh TG 2018-06-20 13:49:13

Use backbone , angular like javascript framework for UI design and fetch the data using rest api. This will remove the java dependency from UI completely.

@Eduardo 2017-12-12 19:45:33

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

@adn.911 2017-11-30 15:59:33

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 logics in the Service layer, and pass the output result to your views through a Controller.

@Razvan 2014-03-15 17:17:18

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.  

@Code_Mode 2017-07-07 20:24:49

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

@Sami Jmii 2011-02-04 10:41:38

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, velocity with JSP as "template engine". The data provider to those tags depends on frameworks that you are dealing with. Struts 2 and webwork as an implementation for MVC Pattern uses OGNL "very interesting technique to expose Beans Properties to JSP ".

@bhanwar rathore 2016-07-15 05:48:33

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

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="" prefix="c" %>
<%@ taglib uri="" prefix="fmt" %>

@Bozho 2010-07-05 07:28:47

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

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

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

@Koray Tugay 2014-07-12 19:47:16

Why do you say JSTL works with request attributes? They can work with attributes in any scope, isn't it?

@tomasb 2011-08-17 20:02:58

Learn to customize and write your own tags using JSTL

Note that EL is EviL (runtime exceptions, refactoring)
Wicket may be evil too (performance, toilsome for small apps or simple view tier)

Example from java2s,

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


create File:java2s.tld in the /WEB-INF/

<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"

<!-- a tab library descriptor -->
<taglib xmlns="">
    <short-name>Java2s Simple Tags</short-name>

    <!-- this tag manipulates its body content by converting it to upper case

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

package com.java2s;

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){
        System.out.println("BodyContent = '" + bc.getString() + "'");

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

            if ( iterations % 2 == 0 ) 

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

        int retValue = SKIP_BODY;

        if ( iterations < howMany ) 
            retValue = EVAL_BODY_AGAIN;

        return retValue;

Start server and load the bodyContent.jsp in browser

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

@tomasb 2011-08-20 20:44:29

though reusability of components is fine it targets some field

@dipu 2012-05-11 16:45:52

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

//process page forwaring if necessary

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

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

            // and so on   

@Dmitriy R 2011-07-12 20:20:17

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.

@WarFox 2011-07-13 07:28:35

JSP is itself a template engine

@RustyTheBoyRobot 2012-06-07 23:52:50

-1 - There are many completely valid reasons to use filters, pre-processors, and post-processors. Yes, you can end up with values that seem mysterious, but not if you understand your architecture.

@kapil das 2013-07-22 05:59:20

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:

  2. EL

@mel3kings 2013-06-14 09:31:31

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 are technically all java codes during runtime. But to answer the question, Tag Libraries are usually used for applying logic (removing Java codes) to JSP pages.

@CsBalazsHungary 2013-01-21 16:04:32

If somebody is really against programming in more languages than one, I suggest GWT, theoretically you can avoid all the JS and HTML elements, because Google Toolkit transforms all the client and shared code to JS, you won't have problem with them, so you have a webservice without coding in any other languages. Even you can 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 JS 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 say worths 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 minimalize it.

@Evan Donovan 2014-04-02 16:46:23

Doesn't really answer the OP's question.

@CsBalazsHungary 2014-04-03 04:17:09

@EvanDonovan well, practically it does give an answer. You don't need to mess with Java codes mixing up with other languages. I admit it uses Java for coding, but it will be translated to JS without Java calls. But the question's scope is how to avoid the chaos of the classic JSP. And GWT technology solves that. I added up this answer since nobody mentioned it, but relevant since it is an alternative to JSP. I didn't want to answer the question's whole scope, but to add a valuable information for people who are ooking for alternatives.

@Thai Tran 2013-01-26 18:07:56

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" %>

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

    <div id="page-header">
    <div id="page-body">
    <div id="page-footer">

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" %>

    <jsp:attribute name="title"> 
        <bean:message key="" />

    [Put your content of the child here]

<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

@Stefan Schubert-Peters 2011-08-14 21:59:10

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:


@David Lavender 2015-05-08 13:51:26

Does this also disable scriptlet comments?: <%-- comment that i don't want in the final HTML --%> . I find it useful to use these rather than HTML comments.

@Martin Carney 2015-07-29 21:55:47

@MrSpoon tracked down an answer for you. As per this answer + comment, this turns off scriptlets <% %>, scriptlet expressions <%! %>, and scriptlet declarations <%= %>. That means directives <%@ %> and comments <%-- --%> remain enabled and usable, so you can still do comments and includes.

@corsiKa 2015-10-06 04:29:25

The disabling of scriptlet directives would be terrible - trim whitespace is invaluable for interacting with legacy systems that freak out with extra whitespace.

@Tobias 2012-05-21 07:51:33

A neat idea from the Python world are 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 above example could look like this:

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

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 i18n as well:

<h1 i18n:translate="">Our special offers</h1>
    <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>

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

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

@BalusC 2012-05-23 18:53:11

JSP has since dec 2009 been succeeded by Facelets which supports this stuff. Facelets is also XML based. See also among others the Facelets chapter in Java EE 6 tutorial and ui:xxx tags in Facelts VDL.

@Tobias 2012-07-31 14:28:09

I don't know Facelets very well, but IIRC it is all about writing classes which implement custom XML elements. The TAL/ZPT way is to have templates which contain true (X)HTML with special attributes which fill or replace the original elements; thus, you can view the working template and see a prototype with nice dummy content. I'm not sure Facelets allow to tweak the original HTML elements (w/o an additional namespace) using custom attributes.

@Tobias 2014-03-23 08:51:49

I just had another look at this Facelets stuff. It contains all sorts of validation facilities etc. and thus follows a completely different philosophy than TAL. The TAL way is, "Keep the logic out of the template as cleanly as possible; have all the complicated stuff be done by the controller which feeds it." You won't ever give a Facelets template to a designer to have him/her tweak it; it's just not possible. Regarding the generated content - it's just like using tal:replace="structure (expression)" attributes all the time.

@Ajay Takur 2012-04-02 13:52:04

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

  1. Use MVC architecture for web application

  2. Use JSP Tags

    a. Standard Tags

    b. Custom Tags

  3. Expression Language

@tanglei 2011-07-11 06:59:59

Just use the JSTL tag and EL expression.

@Chandra Sekhar 2011-06-05 04:23:50

Use JSTL Tag libraries in JSP, that will work perfect.

@msj121 2011-05-20 20:42:34

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.

@tsand 2011-03-22 18:24:53

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.

@mahesh 2011-02-23 06:14:50

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 u can write all programming structures in the form of tags

@Thorbjørn Ravn Andersen 2010-07-05 08:30:06

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.

@Alex 2015-08-17 08:11:57

Old answer but I can not resist to tell that JSF is one of the most horrendous invention in Java space. Try to make a single (HTTP GET like) link and you will understand why.

@Thorbjørn Ravn Andersen 2016-12-22 09:05:27

@Alex but still better. Feel free to recommend something even better.

@tzim 2010-07-05 07:29:18

I'm not sure if i get this correct.

You should read something about MVC. Spring MVC & Struts 2 are the two most common solutions.

@stepanian 2012-02-22 01:02:35

MVC can be implemented with servlets/jsp using many of the above techniques without Spring or Struts.

@xyz 2015-02-03 05:05:57

How it answers the question?

Related Questions

Sponsored Content

79 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

60 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

15 Answered Questions

[SOLVED] Where is Java Installed on Mac OS X?

  • 2013-04-05 04:58:29
  • Thunderforge
  • 588104 View
  • 656 Score
  • 15 Answer
  • Tags:   java macos

62 Answered Questions

[SOLVED] Avoiding != null statements

64 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3786504 View
  • 3203 Score
  • 64 Answer
  • Tags:   java random integer

31 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

45 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

38 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

40 Answered Questions

[SOLVED] Can't start Eclipse - Java was started but returned exit code=13

54 Answered Questions

[SOLVED] Creating a memory leak with Java

Sponsored Content