2

我正在使用 spring 3 struts 2 和 hibernate 开发一个应用程序。登录后我只需要显示页面

它工作正常。当我测试时,我发现了一个大错误

也就是说,我将只需要显示给登录用户的页面的 url 复制并粘贴到其他浏览器中,这意味着它在没有登录的情况下显示页面。

 <%
    String userId= (String)session.getAttribute("userId");             
    System.out.println(userId);                        

    if(userId == null || userId.equals("") ){
        response.sendRedirect("login.jsp");
    }

%>

我已经为所有jsp包含了这个。我知道这不是最佳做法。有没有更好的选择?

我将如何克服这个错误?

4

2 回答 2

0

我还在接受教育,所以知道我的解决方案有多好,但我没有崩溃,所以希望它是正确的

它与@muthu 的代码非常相似

我使用过 JPA-eclipselink 和 Struts2

动作类

String checkLogin = "SELECT user FROM UserEntity user WHERE user.username = :username AND user.password = :password";
Query checkLoginQuery = em.createQuery(checkLogin);
checkLoginQuery.setParameter("username", loginUsername);
checkLoginQuery.setParameter("password", loginPassword);

userEntity = (UserEntity) checkLoginQuery.getSingleResult();

Map sessionMap = ActionContext.getContext().getSession();
sessionMap.put("userEntity", userEntity);

JSP - >所有jsp页面都有这个(错误:如果在浏览器没有关闭时会话没有被终止,则会受到影响)

<%@ taglib prefix="s" uri="/struts-tags" %>
<s:if test="%{#session.userEntity == null}">
            <jsp:forward page="login.jsp"/>
</s:if>


如果我错了,请纠正我

引用此页面

和 RequestDispatcher.forward() 都是我所说的“服务器端”重定向

response.sendRedirect() 就是我所说的“客户端”重定向。

所以服务器端转发对我来说看起来更安全,也许我错了(如果我错过了解释它,我很抱歉,还没有在现实生活中的项目中工作过)

于 2013-09-18T15:37:48.357 回答
0
if(userId == null || userId.equals("") ){
    response.sendRedirect("login.jsp");
}

可能应该有一个返回以防止呈现页面内容:

if(userId == null || userId.equals("") ){
    response.sendRedirect("login.jsp");
    return;
}

javadoc中的任何内容都没有暗示sendRedirect会导致突然退出或导致响应正文未发送到客户端。

可能发生的情况是您的响应包含重定向标头,但还包含您可能不打算发送的页面内容。

于 2013-09-18T15:23:52.663 回答