Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL: check if a string is empty [duplicate]

Tags:

java

jsp

jstl

I'm trying to test in JSTL if a session attribute is empty. However the attribute is empty JSTL sees it as a non-empty attribute.

This is the hardcode I'm trying to replace with JSTL. This code is working correctly:

<% if (request.getAttribute("error") != null) { %>
    <div class="alert alert-danger">
        <strong>Oh snap, something's wrong, maybe the following error could help you out?<br /></strong>
        <%= request.getAttribute("error")%>
    </div>
<% } %>

This is how I replaced it with JSTL. When checked, the error-attribute is not empty, however it is empty.

<c:if test="${not empty sessionScope.error}">
    <div class="alert alert-danger">
        <strong>Oh snap, something's wrong, maybe the following error could help you out?<br /></strong>
        <c:out value="${sessionScope.error}" />
    </div>
</c:if>
like image 622
DaanCelie Avatar asked May 18 '14 10:05

DaanCelie


2 Answers

Add the JSTL library and declare the core taglib:

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

The JSTL equivalent of

<% if (request.getAttribute("error") != null) { %>

is

<c:if test="${not empty error}">
like image 111
gyanu Avatar answered Oct 31 '22 15:10

gyanu


I'm trying to test in JSTL if a session attribute is empty

You have to check in session scope not in request scope.

It should be

<c:if test="${not empty sessionScope.error}">

instead of

<c:if test="${not empty requestScope.error}">

If you are not sure about the scope then use without scope that will look in all scope from bottom to top (page, request, session then finally in application)

<c:if test="${not empty error}">
like image 36
Braj Avatar answered Oct 31 '22 16:10

Braj