Posts Tagged ‘jstl’

[Quicky] JSTL and comparing strings

Saturday, November 29th, 2008

This is the first article in a series of really short articles with problems I come across in my day to day development life. You can recognize these articles by the ‘[Quicky]‘ reference in the title and of course a ‘quicky’ tag is supplied. These ‘quickies’ don’t supply much explanation on why the problem exists, but more how to solve it.

Today I had to compare a variable with a string value using JSTL. Something like:

<c:choose>
  <c:when test="${variable eq "expected value"}">
    something
  </c:when>
</c:choose>

will obviously not work, because the XML becomes invalid. The way to do it however is:

<c:choose>
  <c:when test="${variable eq 'expected value'}">
    something
  </c:when>
</c:choose>

Replacing the double quotes surrounding the string value by single quotes does the trick.

[ztemplates] ZJspRenderer and exposed fields - with JSTL

Saturday, November 15th, 2008

My previous article about ztemplates was about exposed values inside JSP code blocks. There is a also another possible approach and that is to use the JavaServer Pages Standard Tag Library. So let’s rewrite my last code example in the previous article.

Previous example:

<%
if(condition == true) {
 
  // notice the cast to the correct class type
  String message = (String)request.getAttribute("message");
 
  // When debugging it would be nice to check if the object is valid.
  if(message == null) {
 
    throw new Exception("DEBUG: message not exposed by render POJO.");
  }
 
  out.println(message);
}
%>

New example to see if the exposed ‘message’ field was set (with complete XHTML this time) :

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 
<!-- NOTICE: load the tag library -->
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Example</title>
  </head>
  <body>
    <c:choose>
      <c:when test="${message is null}">
        <p>You didn't provide a message!</p>
      </c:when>
      <c:otherwise>
        <p>Here is your message: ${message}</p>
      </c:otherwise>
    </c:choose>
  </body>
</html>

As you can see this is a much more robust way of doing things. Also take a look at this page for a more thorough introduction to JSTL.