2015-04-16 77 views
-1

當我們與servlet通信到applet時,我們如何確保會話信息被保留?Applet和servlet會話管理

也就是說,我們如何管理applet servlet連接中的cookie?

+1

什麼是你談論的「小程序的servlet連接」? Servlet是否會生成包含該applet的HTML頁面,或者是否通過applet創建了一個到servlet的HTTP連接? – Alexander

+0

我們正在創建HTTP連接來連接servlet和applet。 – Zany

回答

0

您可以使用像org.apache.httpcomponents:httpclienthttps://hc.apache.org這樣的API,並使用HttpClient的CookieStore爲請求設置cookie並從響應中讀取它們。之後你必須從某個地方保存的Cookie在你的小應用程序(見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; 
    } 
}