0

我的 GWT+GAE 应用程序中有两个 servlet。一种是“MyServlet 扩展 RemoteServiceServlet”,它处理来自客户端的所有调用。另一个是“上传扩展 HTTPServlet”处理从客户端发布的文件,如下所述:https ://developers.google.com/appengine/docs/java/blobstore/overview

如何从 Upload servlet 访问在 MyServlet 中设置的对象?

//
//MyServlet extends RemoteServiceServlet
//
public User login(String username, String password) {
    User user = null;
    PersistenceManager pm = PMF.get().getPersistenceManager();

    Query query = pm.newQuery(User.class, "username == '" + username + "' && password == '" + password + "'");
    List<User> users = (List<User>) query.execute();
    if (!users.isEmpty()) {
        user = new User();
        User userDB = users.get(0);
        user.setUsername(userDB.getUsername());
        getThreadLocalRequest().getSession().setAttribute("user", user);
    }

    pm.close();
    return user;
}
public void doSomething() {
    //Never returns null. This is good.
    User user = getThreadLocalRequest().getSession().getAttribute("user"); 
    ....
}

//
//Upload extends HTTPServlet
//
public void doPost(HttpServletRequest req, HttpServletResponse res) {
    // Always returns null. WHY?!?
    req.getSession().getAttribute("user");
    ....
}
4

1 回答 1

0

您不能调用getThreadLocalRequest()非 GWT HttpServlet,因为此方法是由 GWT 的 RemoteServiceServlet 提供的。在标准 servlet 中,您应该使用传递给 doGet() 或 doPost() 方法的请求对象,例如:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    if(request.getSession().getAttribute("user")==null) return;
}
于 2012-09-25T14:41:40.580 回答