First I have a Spring 3.0 controller with a method similar to the following.
I’m passing the view an object named “message” and hoping to print that message via the view if it has been set by the “doStuff” method.
@RequestMapping("/index")
public ModelAndView doStuff() {
ModelAndView mav = new ModelAndView();
Map<String, String> message = new HashMap<String, String>();
message.put("message", "Hello World");
mav.setViewName("pages/myView");
mav.addObject("message", message);
return mav;
}
The view is similar to the following,
<%@ page session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<html>
<head>
<title>Test</title>
</head>
<body>
<c:if test="${message.message} != null">
<div class="msg">test1: ${message.message}</div>
</c:if>
<c:if test="${message.message} != ''">
<div class="msg">test2: ${message.message}</div>
</c:if>
<c:if test="${message.message}">
<div class="msg">test3: ${message.message}</div>
</c:if>
<c:if test="not empty ${message.message}">
<div class="msg">test4: ${message.message}</div>
</c:if>
<div class="msg">test5: ${message.message}</div>
</body>
</html>
So far, only “test5” is printing the message, but I only want to print the message if “${message.message}” is not null.
I’ve tried both “http://java.sun.com/jstl/core_rt” and “http://java.sun.com/jstl/core“, but can’t seem to get the “<c:if />” statements to work correctly.
Would anyone have any ideas as to what I’m doing wrong or a better way to do it?
Thanks
Your first two
<c:if>tags should look like this:Note the placement of the != and the } in the test attribute — the condition needs to be inside the braces.
also, the test in #3:
Will only evaluate to true if the value of the message.message is in fact the value “true”. Since it is not (it is “Hello World”), the test fails.
Test #4 is also formatted incorrectly (the “not empty” also needs to be inside the braces)…