2017-03-28 25 views
0

我的服務器代碼:如何跟蹤Java servlet爲Android的請求的會議

public Testing() { 
    super(); 
} 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    doPost(request, response); 
} 


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    HttpSession session = request.getSession(true); 
    Integer accessCount=(Integer)session.getAttribute("sessionCount"); 

     if(accessCount==null){ 
      accessCount=new Integer(1); 
      System.out.println("Welcome for first time...."); 


     }else{ 
     System.out.println("Welcome for "+ accessCount+" time to our website...."); 
     System.out.println("The request id"+session.getId()); 
     accessCount=new Integer(accessCount.intValue()+1); 
    } 
     session.setAttribute("sessionCount", accessCount); 

} 

當我打我的服務器從它正確地跟蹤會話的瀏覽器。輸出是:

歡迎首次....
歡迎了2次到我們的網站....
請求ID:00A24FAF40E130E09F38D52311EF8F1D
歡迎了3次到我們的網站...... 。
請求ID:00A24FAF40E130E09F38D52311EF8F1D
歡迎了4次到我們的網站....
請求ID:00A24FAF40E130E09F38D52311EF8F1D
歡迎了5次到我們的網站....
請求ID:00A24FAF40E130E09F38D52311EF8F1D

但是,當我使用Android模擬器的輸出是打從Android的工作室:

歡迎首次....

歡迎首次。 ...

歡迎首次....

歡迎首次....

我擊中servlet代碼爲

private String getServerResponse(String json){ 
    HttpPost post= new HttpPost("http://10.0.2.2:23130/FirstServlet/welcome"); 
    try { 
     StringEntity entity=new StringEntity(json); 
     post.setEntity(entity); 
     post.setHeader("Content-type", "application/json"); 
     DefaultHttpClient client=new DefaultHttpClient(); 
     BasicResponseHandler handler=new BasicResponseHandler(); 
     try { 
      String response=client.execute(post,handler); 
      return response; 

     } catch (IOException e) { 
      Log.d("JWP", e.toString()); 
     } 
    } catch (UnsupportedEncodingException e) { 
     Log.d("JWP", e.toString()); 
    } 


    return "Unable to contact server......"; 

} 

我給註冊數據,按註冊按鈕連續Android的一面,所以它打印輸出作爲我在服務器端提及。

所以我的問題是,如何在Java servlet中使用HttpSession跟蹤Android請求的會話?

+0

您需要在'Cookie'參數的請求中傳遞'JSESSIONID'。 –

+0

我是一個新的....如果你只是解釋或發送一個linke幫助我在這,管理android請求的會話,謝謝 –

回答

0

看起來問題是你沒有在android端處理cookie,所以JSESSIONID沒有被存儲/發送回服務器。

它已經,因爲我用低級別的HTTP代碼像HttpPost年,但如果我沒記錯的話,你可以設置的cookie有一些很好的更高級別的HTTP與CookieHandler.setDefault(new CookieManager());

處理和REST庫在那裏 - 你應該幫個忙,至少要學習其中的一種。如果你正在做JSON REST(看起來像你),我會建議優秀的Retrofit庫。

當然,你必須弄清楚如何使用cookies,也涉及OkHttp攔截器 - this應該有幫助。