当我们与servlet通信applet时,我们如何确保保留会话信息?
也就是说,我们如何在applet servlet连接中管理cookie?
答案 0 :(得分:0)
您可以使用org.apache.httpcomponents:httpclient
https://hc.apache.org之类的API,并使用HttpClient的CookieStore将Cookie设置为请求并从响应中读取它们。之后,您必须将Cookie存储在applet中的某个位置(请参阅getSessionCookie()
和setSessionCookie()
方法存根):
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.*;
import org.apache.http.client.methods.HttpGet;
public class Connector {
private Cookie getSessionCookie() { /* TODO get cookie from some store (local session, DB, whatever) */ }
private void setSessionCookie(Cookie sessionCookie) { /* TODO set cookie to some store (local session, DB, whatever) */ }
private void connect() {
DefaultHttpClient client = new DefaultHttpClient();
Cookie sessionCookie = getSessionCookie();
if (sessionCookie != null) {
client.getCookieStore().addCookie(jsessionidCookie);
}
client.setRedirectStrategy(new DefaultRedirectStrategy());
// create a GET request to your Servlet in get()
HttpGet get = new HttpGet("http://example.com/your/servlet");
HttpResponse response = client.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
sessionCookie = getJsessionidCookie(client.getCookieStore().getCookies());
// update session cookie
setSessionCookie(sessionCookie);
}
}
private Cookie getJsessionidCookie(List<Cookie> cookies) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("JSESSIONID")) {
return cookie;
}
}
return null;
}
}