我刚刚在我的Google AppEngine/Java + GWT应用程序中启用了Session.我该如何使用它?如何从中获取会话ID和播放所有好处?是否有任何简单登录页面的真实示例,我只是输入LoginName和Password,然后通过RPC调用进入服务器,对数据库进行身份验证并将会话ID发送回客户端.
我已经有以下代码,但不知道下一步该做什么:
GWT登录表格:
public class LoginForm { private final LoginServiceAsync loginService = GWT.create(LoginService.class); VerticalPanel loginVp = new VerticalPanel(); TextBox loginTxt = new TextBox(); TextBox passTxt = new TextBox(); Button loginBtn = new Button("Login"); public Widget getLoginWidget(){ loginBtn.addClickHandler(new ClickHandler(){ public void onClick(ClickEvent arg0) { loginService.authenticateUser(loginTxt.getText(), passTxt.getText(), new AsyncCallback(){ public void onFailure(Throwable caught) { InfoPanel.show(InfoPanelType.HUMANIZED_MESSAGE, "No Connetion", "Problem conneting to the server."); } public void onSuccess(String result) { InfoPanel.show(InfoPanelType.HUMANIZED_MESSAGE, "Session ID", "Your session id is: " + result); GWT.log("Setting up session", null); String sessionID = result; final long DURATION = 1000 * 60 * 60 * 24 * 14; //duration remembering login. 2 weeks Date expires = new Date(System.currentTimeMillis() + DURATION); Cookies.setCookie("sid", sessionID, expires, null, "/", false); } } ); } }); loginVp.add(loginTxt); loginVp.add(passTxt); loginVp.add(loginBtn); return loginVp; } }
RPC Servlet:
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService{ //Sends back to the client session id public String authenticateUser(String login, String password){ String sessionId = new String(); // TODO: figure out how to work with session id in GAE/J sessionId = "How to get session id?"; return sessionId; } public Boolean checkIfSessionIsValid(String sessionId){ //TODO: figure out how to check user's credentials return true; } }
任何正确方向的提示都会有所帮助.谢谢.
启用会话支持为您提供标准的Servlet HttpSession.
这将通过cookie(称为JSESSONID)进行跟踪,该cookie由封面下的servlet容器管理.您无需关心会话ID.
然后,您可以设置将与会话关联的属性(服务器端)(以便以后可以检索它们).
HttpServletRequest request = this.getThreadLocalRequest(); HttpSession session = request.getSession(); // in your authentication method if(isCorrectPassword) session.setAttribute("authenticatedUserName", "name"); // later if (session.getAttribute("authenticatedUserName") != null)
这也适用于GWT的Ajax请求.有关更多详细信息,请参阅任何Servlet教程.
GAE上的会话(与其他servlet引擎相比)的缺点是它们每次都被序列化并从数据库加载,这可能很昂贵,特别是如果你在那里放了大量数据.
以下是如何在GAE中进行会话的方法:
this.getThreadLocalRequest().getSession();