Genom
Genom

Reputation: 158

How to terminate a request in JSP (not the "return;")

I am programming a website with JSP. There are pages where user must be logged in to see it. If they are not logged in, they should see a login form. I have seen in a php code that you can make a .jsp page (single file), which checkes, whether the user is logged in or not. If not it will show the login form. If the user is logged in, nothing will be done. So in order to do that I use this structure in my JSPs:

Headers, menus, etc. etc... normal stuff which would be shown such as body, footer to a logged in user.

This structure is very easy to apply to all webpages. So I don't have to apply checking algorithm to each webpage! I can simply add this "" and the page is secure!

So my problem is that if the user is not logged in, then only the log in form should be shown and the footer. So code should bypass the body. Therefore structured my checklogin.jsp so:

If user is not logged in show the login form and footer and terminate request. The problem is that I don't know how to terminate the request... If I use "return;" then only the checklogin.jsp stops but server continues to process parent page! Therefore page has 2 footers! (1 from parent page and 1 from checklogin.jsp). How can I avoid this?

(There is exit(); in php for this by the way!)

Thanks for any suggestions!

Edit 1: I also have tried response.getOutputStream().close(); but didn´t seem to work.

Edit 2: There is an analog to what I need in PHP: exit();

Upvotes: 1

Views: 1219

Answers (2)

Genom
Genom

Reputation: 158

Ok the answer for my question is out.close(); This simply ends the response. Thanks to JB Nizet to point out another aspect about this problem.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691835

You do it as you would do it in any programming language:

<c:choose>
    <c:when test="userIsLoggedIn">
        normal header, body
    </c:when>
    <c:otherwise>
        login form
    </c:otherwise>
</c:choose>
footer

But the main problem is that you shouldn't do that at all. JSPs should be used to generate markup. Not to check whether the user is logged in and display a page or another depending on the result. You should do that in Java, in a servlet which dispatches to the appropriate JSP. That's the MVC pattern.

And since it's something that should be done for almost all the requests, you should even do that in a servlet filter. A filter is mapped to a set of URLs, like a servlet, and intercepts all the requests to these URLs. The filter would thus check if the user is logged in and forward or redirect to the login page if not. If the user is authenticated, it wouldn't do anything except letting the request go to the servlet/JSP mapped to the URL.

Read http://www.oracle.com/technetwork/java/filters-137243.html for example, to know more about filters.

Upvotes: 1

Related Questions