简体   繁体   English

如何在JSP中实现登录系统

[英]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. 一个非常基本的JSP问题,因为我仍在尝试理解正确的处理方式。

I'm working on a web app which requires users to log in before working. 我正在使用一个Web应用程序,该应用程序要求用户在工作之前先登录。 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). 我选择的方法是在每页顶部添加一些代码,尝试从会话中获取用户对象,如果不存在,则重定向到登录名(我有一个User对象为存在的用户存储在会话中,其中包含其他详细信息(例如权限)。

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. 我不知道您是否有这种选择,但是使用Java EE声明式安全性可以使您不必将验证代码放入每个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. 想法是,在web.xml中指定安全规则,例如: URL模式只能由角色的用户访问。然后,当用户尝试访问受保护的资源时容器将发出挑战。 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. 是的,JSP被编译为Servlet子类。 The proper way to return early is to simply place a "return;" 早日返回的正确方法是简单地放置“返回”; in your JSP. 在您的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! 最终很容易无意间忘记了1个JSP顶部的include,然后您最终不小心允许该页面上的GUEST用户!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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