如何在Java JSP中动态更改登录和注销链接?

huangapple go评论67阅读模式
英文:

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 LoginServlet 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(&quot;ATTRIBUTE&quot;)==null){//Make sure that when the user logs in, you set the attribute
    //They are not logged in
    response.sendRedirect(&quot;Login.jsp&quot;);
}else{
    //They are logged in
    response.sendRedirect(&quot;Home.jsp&quot;);
}

If you want to display whether the user is logged in or logged out, you can use the &lt;c:choose&gt; tag like so:

&lt;c:choose&gt;
    &lt;c:when test=&quot;${sessionScope.username != null}&quot;&gt;
        You are logged in!
    &lt;/c:when&gt;
    &lt;c:otherwise&gt;
        You are not logged in :(
    &lt;/c:otherwise&gt;
&lt;/c:choose&gt;

Don't forget to important the taglib above the &lt;head&gt;:

&lt;%@ taglib uri=&quot;http://java.sun.com/jsp/jstl/core&quot; prefix=&quot;c&quot;%&gt;

huangapple
  • 本文由 发表于 2020年9月29日 19:29:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64118697.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定