我成功使用了Google Cloud Endpoints。现在对于自定义用户身份验证,我想使用HTTPSession。问题是,初始会话未在以后的调用中重用,并且创建了新会话(我可以从数据存储区管理员看到会话全部存在,_AH_SESSION实体)。按照文档中的说明,我在appengine-web.xml中启用了它:
<sessions-enabled>true</sessions-enabled>
我制作了一些示例代码来缩小范围:
@Api(name = "loginService", version = "v0.1.5")
public class LoginService {
private static final Logger log = Logger.getLogger(LoginService.class.getName());
@ApiMethod(name = "login", path= "login")
public LoginResponse login(HttpServletRequest req)
{
HttpSession session = req.getSession(false);
if(session == null){
log.warning("creating new session");
session = req.getSession(true);
}
LoginResponse resp = new LoginResponse();
resp.statusCode = 200;
resp.statusMessage = "SessionId:" + session.getId();
return resp;
}
@ApiMethod(name = "show", path= "show")
public LoginResponse show(HttpServletRequest req)
{
//session should exist when calling LOGIN first
HttpSession session = req.getSession(false); //NULLPOINTER since session from login is not being reused/found!
LoginResponse resp = new LoginResponse();
resp.statusCode = 200;
resp.statusMessage = "SessionId:" + session.getId();
return resp;
}
public class LoginResponse implements Serializable{
public int statusCode;
public String statusMessage;
}
}`
首先,我调用login方法,这会创建一个新会话并打印会话ID。然后在下一个请求中(都使用Postman - 它应该跟踪会话 - 在Chrome中作为API资源管理器)我称之为&#39; show&#39;端点,并且之前的会话不再存在,因此空指针异常。
在this post的评论中,用户mikO表示端点不会保留会话。这是什么原因?我真的不明白背后的原因。当我刚刚部署一个常规的&#39; appengine上的servlet,它使用Postman工作或只是浏览..(通过调用getter两次测试,我看到前一个会话正在被拾取),所以似乎该帖子中的评论可能是正确的,但我真的不明白为什么。没有端点的工作代码:
public class LoginServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(LoginServlet.class.getName());
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession s = request.getSession(false);
if (s == null) {
log.warning("creating new session");
s = request.getSession(true);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + s.getId() + "</h1>");
}
}
谢谢!