简体   繁体   中英

How to implement a login system in JSP

A pretty basic JSP question, since I'm still trying to understand the right way to do things.

I'm working on a web app which requires users to log in before working. What I'd like to happen is, anytime a user that isn't logged in tries to access any page (other than the login page), the user will be redirected to my login page.

The approach that I've chosen is just to have a bit of code at the top of each page, attempting to grab the user object from the session, and if it doesn't exist, redirect to the login (I have a User object stored in the session for users that exist, which contains other details like permissions).

Is this the proper way of going about doing authentication? Or are there more standard ways I should be looking into?

EDIT: I decided to split this question into two questions, since one was more of a best-practices question and another was a purely technical one. Thanks for the responses.

I don't know whether you have this alternative, but using the Java EE declarative security would free you from needing to put authentication code into every JSP.

The idea is that in your web.xml you specify security rules, such as: this URL pattern can only be accessed by users in that role.The container will then challenge when users attempt to access the protected resources. You can specify your own login page for use when the users are challenged.

I think this is much perferable to coding your own login.

Here's a link to a description of how to do this.

Yes, JSPs are compiled down to servlet subclasses. The proper way to return early is to simply place a "return;" in your JSP.

Having said that, I think you should consider other authentication solutions. Its very easy to end up inadvertantly forgetting the include at the top of 1 JSP, and then you end up accidentally allowing GUEST users on that page!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM