2

I want to check if the user is logged in or not using JSTL.

I tried the following code:

<c:if test="${sessionScope.logged_in == null}">
      <c:redirect url="index.jsp"></c:redirect>
</c:if>


I have also tried the following code but it throws an IllegalStateException:

<c:if test="${empty user}">
    <b>you are not logged in</b>
<c:redirect url="index.jsp"></c:redirect>
</c:if>

but it is not working.

How can I implement the following code in JSTL:

<%
   String logged_in = (String) session.getAttribute("logged_in");
   if (logged_in == null) {
        response.sendRedirect("index.jsp");
   }
%>
informatik01
  • 16,038
  • 10
  • 74
  • 104
Vishal Anand
  • 581
  • 3
  • 10
  • 22
  • 2
    http://stackoverflow.com/tags/servlet-filters/info – BalusC Feb 08 '13 at 19:54
  • The @BalusC suggested variant (see the example in his link) is the more preferred solution. It is the common practice to use servlet filters for the things like a login check. But of course it's up to you ... – informatik01 Feb 28 '13 at 23:20
  • @informatik01 The question is about JSTL but not about filters. – Alex Feb 28 '13 at 23:32
  • @Alexey Yes, I agree that you gave the answer for the question he asked in the last sentence. But the **preferred and most common** way of checking if user is logged in or not is by using servlet filters. I just gave him a hint, you know – informatik01 Feb 28 '13 at 23:35
  • @informatik01 In this case it can be some interceptor (spring mvc) for example because we don't know anything about backend for this question. – Alex Feb 28 '13 at 23:41
  • @Alexey Maybe, although no mentioning of Spring was seen in the question. btw interesting answer here as well: [Spring HandlerInterceptor vs Servlet Filters](http://stackoverflow.com/a/8006367/814702). Again, as I understand, BalucS just gave him a link to help him see the direction to move for. And I agreed with that. No worries ) – informatik01 Feb 28 '13 at 23:45
  • 1
    Indeed. The OP is using the wrong tool for the job. – BalusC Feb 28 '13 at 23:59
  • 1
    Thanks for the help, and I liked the concept of filters :D – Vishal Anand Mar 01 '13 at 17:40

1 Answers1

3

Try this:

<c:if test="${empty logged_in}">
<c:redirect url="index.jsp"></c:redirect>
</c:if>

Alex
  • 11,451
  • 6
  • 37
  • 52