Thursday 7 June 2012

Basic JSP Tags

Basic JSP Commands

Here are a load of basic jsp tags that I'll add to over time.  Initially though, it'll just cover the real basics

In a JSP page there are certain elements which are always available.  These include

request - HttpServletRequest
session - HttpSession

For example to view the username of the currently logged in user you can use

    <%= request.getUserPrincipal().getName() %>

You can also do this with the c:out command below if you use the pageContext first.

JSP Tags

To use the basic JSP tags you'll need to include the import at the top of the jsp page.

    <%@ taglib prefix="c" uri="" %>  


Use this to 'print' to the screen eg

    <c:out value="${modelValue}"/>

where modelValue is put into the ModelMap in the controller.


Use this to conditionally add items

    <c:if test="${myValue == 'Value'}">
        do something

c:choose / c:when / c:otherwise

This is the equivalent to the if - else if - else statement

        <c:when test="${myValue == 'Value'}">
            do something
        <c:when test="${myValue == 'AnotherValue}">
            do something else
            do the fall back action


This is a really useful tag which allows you to just create a link and the tag will take care of the server name, port and application context

    <c:url value="/my_link" />

you can also add attributes

    <c:url value="/my_link"> 
        <c:param name="link" value="${linkId}" /> 


This is a basic iterator for looping through lists etc

    <c:forEach var="item" items="${itemList}" varStatus="status">

        ${status.first ? 'Start' : ''}

        ${status.index}: ${}

        ${status.last ? 'End' : ''}



It is occasionally necessary to create a variable that is used by other jsp commands or tags. You can do this by using the c:set tag, for example

    <c:set var="linkId" value="${}"/>
You can set different scopes for these by using the scope="..." attribute,
    <c:set var="linkId" scope="session" value="${}" />
but by default it is page-scope only.

No comments:

Post a Comment