0

My JSP page accesses several attributes, as in the following section:

    <div id="ep-error-title">Error ${errorCode}: ${errorMessage} <!-- error number and text -->
    </div>

What I want to do is to be able to access the errorCode within JSP statements, so I can do something like:

    <% if ("1".equals(errorCode)) { %>
    <%@ include file="stuffFor1.inc" %>
    <% } else { %>
    <%@ include file="stuffForEverythingElse.inc" %>
    <% } %>

The problem is the EQUAL test; how do I access the value (which was shown by ${errorCode} when outside the JSP section) when I'm inside the JSP section? Sorry if this seems obvious, but I haven't worked hardly at all with either Spring or JSP.

1 Answers1

1

I would suggest using the JSP Standard Tag Library (JSTL) for branching logic rather than embedding scriptlets. There are many tutorials available online, but basically you need to add a project dependency:

If you are building with Maven it would look like:

<dependency>
  <groupId>javax.servlet.jsp.jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

Include it at the top of your JSP pages:

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

You can then use JSTL elements such as <c:if>, <c:choose>, <c:when>, and <c:otherwise>. For example, in your situation it looks like you might do the following:

<c:choose>
  <c:when test="${errorCode == '1'}">
    <%@ include file="stuffFor1.inc" %>
  </c:when>
  <c:otherwise>
    <%@ include file="stuffForEverythingElse.inc" %>
  </c:otherwise>
</c:choose>

Having said all that... if you really want to access the variable in a scriptlet, see this answer.

Community
  • 1
  • 1
Mike Muske
  • 323
  • 1
  • 16