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="http://java.sun.com/jsp/jstl/core" %>  
 

c:out

Use this to 'print' to the screen eg

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

where modelValue is put into the ModelMap in the controller.

c:if

Use this to conditionally add items

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

c:choose / c:when / c:otherwise

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

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

c:url

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}" /> 
    </c:url>

c:forEach

This is a basic iterator for looping through lists etc

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

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

        ${status.index}: ${item.name}

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

    </c:forEach>

c:set

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


No comments:

Post a Comment