有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java servlet中跟踪安卓请求的会话

我的服务器代码是:

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);
    
}

当我从浏览器点击服务器时,它会正确地跟踪会话。输出为:

Welcome for first time....
Welcome for 2 time to our website....
The request id: 00A24FAF40E130E09F38D52311EF8F1D
Welcome for 3 time to our website....
The request id: 00A24FAF40E130E09F38D52311EF8F1D
Welcome for 4 time to our website....
The request id: 00A24FAF40E130E09F38D52311EF8F1D
Welcome for 5 time to our website....
The request id: 00A24FAF40E130E09F38D52311EF8F1D

但当我使用Android Emulator从Android Studio点击它时,输出是:

Welcome for first time....

Welcome for first time....

Welcome for first time....

Welcome for first time....

我点击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端连续按下注册按钮,所以它会像我在服务器端提到的那样打印输出

所以我的问题是,如何在JavaServlet中使用HttpSession跟踪Android请求的会话


共 (1) 个答案

  1. # 1 楼答案

    问题似乎在于,您没有在android端处理cookie,因此JSESSIONID没有被存储/发送回服务器

    我已经多年没有使用像HttpPost这样的低级HTTP代码了,但如果我没记错的话,可以使用CookieHandler.setDefault(new CookieManager());设置cookie处理

    有一些非常好的高级HTTP和REST库——你应该帮自己一个忙,至少学习其中一个。如果您正在使用JSON REST(看起来是这样),我建议您使用优秀的改装库

    当然,你也必须弄清楚如何进行改造以使用cookie,这涉及到OkHttp拦截器-this应该会有所帮助