如何在Google Appengine / Java中跨不同servlet访问会话

时间:2015-12-06 05:17:28

标签: java jsp google-app-engine session servlets

我读到了一些地方,在一个上下文中设置的会话属性不能被另一个上下文访问。我假设这里的上下文是一个servlet。

我在这里有一个场景,我有一个Appengine servlet类,我在其中设置了一些session属性。

public class LoginServlet extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request,
        HttpServletResponse response) throws IOException{
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        HttpSession session = request.getSession(true);
        session.setAttribute("username", username);
        session.setAttribute("password", password);

        System.out.println(session.getId());

        // response.getWriter().println("Done");
        response.sendRedirect("/dashboard.jsp");

    }
}

正如您所看到的,最后我将重定向到另一个页面。我在哪里尝试获取会话属性。但它总是返回null。 dashboard.jsp如下所示。

<%@ page import="com.bullbull.Employee" %>
<%@ page import="com.googlecode.objectify.Key" %>
<%@ page import="com.googlecode.objectify.ObjectifyService" %>

<%


HttpSession sesn = request.getSession(true);

System.out.println(sesn.getAttribute("username"));

%>


<html>
  <head>
    <title>Dashboard</title>

登录后,它始终打印为空。

enter image description here

我知道,我在某处理解某些事情是错误的。请帮忙!

谢谢!

2 个答案:

答案 0 :(得分:0)

我想你可能错过了在appengine-web.xml中配置会话

<sessions-enabled>true</sessions-enabled>

https://cloud.google.com/appengine/docs/java/config/appconfig#Java_appengine_web_xml_Enabling_sessions

来自文档

App Engine includes an implementation of sessions, using the servlet session interface. The implementation stores session data in the App Engine datastore for persistence, and also uses memcache for speed. As with most other servlet containers, the session attributes that are set with session.setAttribute() during the request are persisted at the end of the request.

This feature is off by default. To turn it on, add the following to appengine-web.xml:

<sessions-enabled>true</sessions-enabled>

答案 1 :(得分:0)