Vpp Man
Vpp Man

Reputation: 2546

JSP - exit executing the rest of the code

In the first line of my JSP page, I check for a session value is null. If null redirect back to login page.

When i tested it by loggingout and checked that page, it give a org.apache.jasper.JasperException: java.lang.NullPointerException error.

So how to exit the code just after the sendRedirect line ?

Code:

<%
   if((session.getAttribute("user_type")==null) || (!session.getAttribute("user_type").equals("user")))
    {
        response.sendRedirect("login.jsp");

        //prevent executing rest of code.
    }
%>

<html>
  <head>
    .......

To logout, I use only: session.invalidate();

Upvotes: 2

Views: 9441

Answers (3)

Steven
Steven

Reputation: 1243

Yes. Simply add the following line:

if ( true ) return;

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

Your JSP code is equivalent to:

if (someCondition) {
    redirect();
}
doPlentyOfOtherThings();

If you don't want to do plenty of other things, the code should be

if (someCondition) {
    redirect();
}
else {
    doPlentyOfOtherThings();
}

So it should look like that:

<%
    if((session.getAttribute("user_type")==null) || (!session.getAttribute("user_type").equals("user")))
    {
        response.sendRedirect("login.jsp");
    }
    else
    {
%>
<html>
    <head>
    .......
<%   } %>

Except that

  • you shouldn't use scriptlets, but the JSP EL and the JSTL in JSP pages
  • such a logic shouldn't be in a JSP, which should only have to generate markup. It should be in a servlet of action of your preferred MVC framework, which would redirect or dispatch to the JSP.

Upvotes: 2

Vpp Man
Vpp Man

Reputation: 2546

After doing some more debugging, I found where this problem was causing.

I have a jsp:include tag. And in the main code, I only assigned the page to include if user is valid(logged in). So, when user is loggedout, this tag was still trying to include it(I used a variable to pass the pagename).

What I have added:

<%
   if(session.getAttribute("user_type")!=null)
    {
%>
       <jsp:include.... />
<%
    }
%>

Now this jsp tag will not be considered during execution when user is not valid.

Upvotes: 0

Related Questions