Search code examples
javajspweb-applicationsjstljsp-tags

Use of JSTL in a web app


I am a front end or UI developer with limited understanding of Java. I have a java based web app with JSTL used in it..I would like to understand the exact use of JSTL. Is it always used within JSP pages and is it used only for getting data from the database. Could you please explain with some basic examples..


Solution

  • Is it always used within JSP pages

    Yes.

    ... and is it used only for getting data from the database.

    No. In fact, in most cases it is bad practice to access the database from a JSP, using JSTL or using other means (e.g. scriptlets).

    does it mean like most JSP would have an associated Java file like 1-1 mapped, where the logic to get data using SQL query is written and is given to the JSP page.

    Sort of. But there is not necessarily a 1 to 1 mapping:

    • Not all JSPs need to access the database.
    • A Java servlet may use multiple JSPs to render different output pages.
    • Different servlets may share a single JSP; e.g. to render a common error message page.

    If yes, what exactly is the role of JSTL code within the JSP.

    The aim of a JSP is to render output; typically HTML pages, but it could be anything text-based. JSTL is used within JSPs when the the output rendering logic is too complicated or messy to express using JSP EL.


    UPDATE

    The old-fashioned alternative to JSTL and JSP EL is to embed Java code ... i.e. scriptlets ... in the JSPs. For example:

    <c:if test="${a == 'true'}">
        hi
    </c:if>
    

    is equivalent to something like this:

    <% if ("true".equals(context.findAttribute("a")) { %>
        hi
    <% } %>
    

    Also for JSTL use, from what I understand, it is used within the JSP for dynamic HTML rendering through if-else statements.

    You are describing HTML whose structure and content depends request parameters, configuration parameters, data fetched from the database and so in. This is the primary uses of JSTL.

    However, this is NOT what is normally referred to as "Dynamic HTML". Dynamic HTML is where the browser changes the HTML of the currently displayed page, for e.g., when Javascript embedded in the page changes displayed page by modifying the DOM.