Some useful JSP Expression Language hacks in JSP

j2ee

Some useful JSP Expression Language hacks in JSP

If you have JSTL in your classpath(by including JSTL.jar and standard.jar in your classpath), then you need to write below taglib directive so that you can use JSTL tags.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%/>

1. Redirecting to other resource in application

<c:redirect url="/hello.html"/>

where, hello.html is another resource.

2. Looping model data in JSP and printing to console

<c:forEach items="${modelList}" var="anoop">
	<% System.out.println(pageContext.findAttribute("anoop") ); %>
</c:forEach>

where, modelList is a list passed to the jSP as model.

3. To get the context URL path in JSP page via JSP EL

<a href="${pageContext.request.contextPath}/main/welcome.html">Click Here </a>

 

4. To get value from session in JSP page via JSP EL

${sessionScope.username}

where, sessionScope is an implicit object provided by JSP Expression language, and username is an attribute which was used to store some value in session object.

5. JSTL iterate over map

<c:forEach var="country" items="${capitalMap}">
    Country: ${country.key}  - Capital: ${country.value}
</c:forEach>

where, capitalMap is a map that was set in model passed to JSP.

6. Mixing JSTL EL with javascript

<script>
var test = '${jobId}';
var something = '<c:out value="${sessionScope.something}"/>';
</script>
where, jobId is a model variable, and something is an attribute set in session object.
 
<c:if test="${(param.error != null) && (errorMessage!=null)}">
  <script type="text/javascript">
   window.onload = function() {
    toast('${errorMessage}');
  };
  </script>
</c:if>

 

7. Check if request parameter is present in JSP

<c:if test="${not empty param.P1}">
    hello there
</c:if>

where, param is request paramaters object, and P1 is a request parameter in URL.

8. JSTL string contains

<c:if test="${fn:contains(testString, 'test')}">
  do your stuff
</c:if>

JSTL includes a number of standard functions, most of which are common string manipulation functions. Following is the syntax to include JSTL Functions library in your JSP:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

 

9. JSTL get servlet path

<c:set value="${requestScope['javax.servlet.forward.servlet_path']}" var="servletPath"/>

 

10. JAVA style integer casting and ternary operation in JSP

<fmt:parseNumber var="totalPagesRolesList" integerOnly="true" type="number" value="${((model.resultCount %  model.recordsPerPage) ==0) ? (model.resultCount /  model.recordsPerPage) : ((model.resultCount /  model.recordsPerPage) + 1)}" />

The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites. Following is the syntax to include Formatting library in your JSP:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

 

11. Casting a number into string in JSP

Set it as body of <c:set>. It will implicitly be converted to String.

<c:set var="totalPagesRolesListAsString">${totalPagesRolesList}</c:set>

 

12. JSTL casts string to integer when comparing

<c:if test="${'1' eq 1}">
	<input type="hidden" value="hallo"/>
</c:if>

The EL supports set of rules to coerce the type of the resulting value to the expected type. Not sure if string 1 is coerced to integer, or integer is coerced to string 1, but its upto the rules of EL. Let them take care of it.

 

13. JSTL get indexOf string

<c:set value="Hello brother!" var="canonical"/>
<c:set value="${fn:indexOf(canonical, 'hello')}" var="indexOfHello"/>

JSTL includes a number of standard functions, most of which are common string manipulation functions. Following is the syntax to include JSTL Functions library in your JSP:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

 

14. JSTL substring

<c:set value="Hello brother!" var="canonical"/>
<c:set value="${fn:substring(canonical, 0, 3)}" var="subString"/>

JSTL includes a number of standard functions, most of which are common string manipulation functions. Following is the syntax to include JSTL Functions library in your JSP:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

 

15. Get domain name in JSP

<c:set value="<%=request.getServerName().toString()%>" var="domainName" />

 

About Anoop Kumar Rai