英文:
How to change login and logout links dynamically in Java jsp?
问题
我在这个论坛上有一个类似的问题,当我学习用JSP构建一个位于“顶部菜单栏”上的登录/注销时。我想知道是否可以使用会话的相同方式,并且这个会话对象是应该在LoginServlet
还是SessionServlet
中以控制这个UI行为,如果我在会话中使用MongoDB,我如何实现这个结果?
英文:
I have this similar question in this forum while learning jsp to build a login/logout on the top menu bar
. I wonder is it the same way to use session and should this session object be in LoginServle
t or SessionServlet
to control this UI behaviour, and how can I achieve this result if I use MongoDB with the session?
答案1
得分: 1
这取决于您的登录/登出将导向何处。从宏观上看,这实际上并不重要。例如,如果您选择将其指向LoginServlet,您可以像这样处理:
HttpSession session = request.getSession();
if(session.getAttribute("ATTRIBUTE")==null){//确保用户登录时设置了属性
//他们未登录
response.sendRedirect("Login.jsp");
}else{
//他们已登录
response.sendRedirect("Home.jsp");
}
如果您想要显示用户是已登录还是已登出,您可以使用`<c:choose>`标签,像这样:
<c:choose>
<c:when test="${sessionScope.username != null}">
您已登录!
</c:when>
<c:otherwise>
您未登录 :(
</c:otherwise>
</c:choose>
不要忘记在`<head>`标签之前导入标签库:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
英文:
It depends where your login/logout will lead to. In the grand scheme, it really doesn't matter. For example, if you chose to direct it towards LoginServlet, you would handle it like so:
HttpSession session = request.getSession();
if(session.getAttribute("ATTRIBUTE")==null){//Make sure that when the user logs in, you set the attribute
//They are not logged in
response.sendRedirect("Login.jsp");
}else{
//They are logged in
response.sendRedirect("Home.jsp");
}
If you want to display whether the user is logged in or logged out, you can use the <c:choose>
tag like so:
<c:choose>
<c:when test="${sessionScope.username != null}">
You are logged in!
</c:when>
<c:otherwise>
You are not logged in :(
</c:otherwise>
</c:choose>
Don't forget to important the taglib above the <head>
:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论