如何检查或不Servlet中的一个用户是否登录? [英] How to check whether a user is logged in or not in Servlets?

查看:115
本文介绍了如何检查或不Servlet中的一个用户是否登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的Java Servlet 的我想以编程方式检查用户是否登录不会

In a Java Servlet I want to check programmatically whether a user is logged in or not.

推荐答案

的<一个href=\"http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal%28%29\"相对=nofollow> HttpServletRequest的#getUserPrincipal() 在对方的回答指出,只有当你使用的Java EE提供的容器管理的安全概述的适用这里

如果你然而homegrowing自​​己的安全,那么你需要依靠的 的HttpSession 。这并不难,这里是一个概述,你需要对每一个步骤来实现的:

If you're however homegrowing your own security, then you need to rely on the HttpSession. It's not that hard, here is an overview what you need to implement on each step:

在登录,获得用户从数据库并将其存储在会话中的 servlet的 的doPost()

On login, get the User from the DB and store it in session in servlet's doPost():

User user = userDAO.find(username, password);
if (user != null) {
    session.setAttribute("user", user);
} else {
    // Show error like "Login failed, unknown user, try again.".
}

在注销,只是在无效servlet的的doPost会话()。它会破坏了会议,并清除所有属性。

On logout, just invalidate the session in servlet's doPost(). It will destroy the session and clear out all attributes.

session.invalidate();

要检查是否有用户终止或没有登录,创建的 URL模式覆盖受限制的页面,如>过滤 /安全/ * /保护/ * ,等等贯彻的doFilter()象下面这样:

To check if an User is logged in or not, create a filter which is mapped with an url-pattern which covers the restricted pages, e.g. /secured/*, /protected/*, etcetera and implement doFilter() like below:

if (session.getAttribute("user") == null) {
    response.sendRedirect(request.getContectPath() + "/login"); // Not logged in, redirect to login page.
} else {
    chain.doFilter(request, response); // Logged in, just continue chain.
}

这就是基本上所有。

That's basically all.

  • How to redirect to Login page when Session is expired in Java web application?
  • How to handle authentication/authorization with users in a database?

这篇关于如何检查或不Servlet中的一个用户是否登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆