【问题标题】:The View is not reading the current session视图未读取当前会话
【发布时间】:2012-09-22 21:50:20
【问题描述】:

这是我的 servlet,它创建会话并将 accessCount 存储到当前会话

@WebServlet("/ShowSession.do")
public class ShowSession extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        HttpSession session = request.getSession();

        String header;
        Integer accessCount  = (Integer)request.getAttribute("accessCount");

        if(accessCount == null){
            accessCount = new Integer(0);
            header = "Welcome New Comer";
        }else{
            header = "Welcome Back!";
            accessCount = new Integer(accessCount.intValue() + 1 );
        }

        //Integer is immutable data structure. so we cannot
        //modify the old one in-place,Instead, you have to
        //allocate a new one and redo setAttribute
        session.setAttribute("accessCount", accessCount);
        session.setAttribute("heading", header);
        RequestDispatcher view = getServletContext().getRequestDispatcher("/showsession.jsp");
        view.forward(request, response);
    }
}

这是打印出该会话内容的视图

<body>
    <%
        HttpSession clientSession = request.getSession();
        String heading = (String) clientSession.getAttribute("heading");
        Integer accessCount = (Integer) clientSession
                .getAttribute("accessCount");
    %>
    <h1>
        <center>
            <b><%=heading%></b>
        </center>
    </h1>
    <table>
        <tr>
            <th>Info type</th>
            <th>Value</th>
        <tr>
        <tr>
            <td>ID</td>
            <td><%=clientSession.getId()%></td>
        </tr>
        <tr>
            <td>Creation Time</td>
            <td><%=new Date(clientSession.getCreationTime())%></td>
        </tr>
        <tr>
            <td>Time of last Access</td>
            <td><%=new Date(clientSession.getLastAccessedTime())%></td>
        </tr>
        <tr>
            <td>Number OF Access</td>
            <td><%=accessCount%></td>
        </tr>
    </table>
</body>

问题是,即使我已经访问了很多次,它仍然返回我一个 accessCount == 0,

我在 localhost:8080/someFolderName/ShowSession.do 访问

【问题讨论】:

    标签: model-view-controller jsp session jakarta-ee servlets


    【解决方案1】:

    您正在从请求中获取 accessCount 初始值。您应该从会话中检查它。

    //Bad!
    Integer accessCount  = (Integer)request.getAttribute("accessCount");
    //Good (maybe)
    Integer accessCount  = (Integer)session.getAttribute("accessCount");
    

    【讨论】:

    • 哦!接得好!使用请求而不是会话!谢谢!
    • 但是等等,它仍然返回 null
    • 第一次返回null。检查第二次,然后继续。另外,请确保您没有再次设置会话变量和/或清理整个会话。
    • 但在我的控制器上,如果它为空,我将其设置为 0 值
    • 所以你只是刷新页面以确保,对吧?
    猜你喜欢
    • 2011-07-26
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多