Luis Alves
Luis Alves

Reputation: 1286

Detect if user was authenticated

I'm trying to allow my website user to authenticate them selves in order to be able to navigate throw my website. At the moment I've a form-based authentication on JBOSS AS7 and it's working fine. So, now I just wanna fix some problems. Well I set the login page as /login.jsp, and what I noticed is that an authenticated user can navigate again to this page and login again. I want to fix this by detecting whether the user is authenticated or not and if he is, I want to redirect him to another page (cause the login page makes no sense to an authenticated user). How can I do this using JSP? Can I do this directly on the login.jsp or do I need a servlet in the middle?

Also (a question a part) how can I logout the user?

Thanks a lot!

Upvotes: 0

Views: 660

Answers (1)

tgkprog
tgkprog

Reputation: 4598

You have a couple of questions, which makes me think the first thing you should do is spend 5-6 hours going thru a starter J2EE and maybe java collections / Core java tutorial.

Usually sites store logged in statue in the session. So the first think you do is session.getAttribute("user");

This could point to a boolean (logged in or not) OR better a class that holds info about current user, one of which could be logged in status.

In log page if already logged in - google for page redirect to make them go to another page (an if check before rendering any output - no javascript/ css anything for redirect to work)

For rest of site its most efficient to use a Filter that checks if user is logged in, with following rules: 1. If user is at /login or /logout or /publicArea do nothing (no need to check if logged in) 2. else if not logged in redirect to login page

This way do not need to add this code in all jsps. The Java filter can be configured to be called for * (all) requests.

To log out simply remove the session attribute or make the boolean inside the pojo as false.

Java session

Redirecting a request using servlets and the "setHeader" method not working

Java EE tutorial

Upvotes: 1

Related Questions