2017-02-16 67 views
0

我用java的主要servlet来创建会话变量。但我是 无法从java main2 servlet访问该会话变量。HttpSession不工作?

前端是Angular2和后端是用java

Angular2部分

getsess(){ 
     console.log("button press") 
      var url = "http://localhost:8000/demoApp/main"; 
      var header=new Headers(); 
      header.append('Content-Type','application/x-www-form-urlencoded'); 
      let body=new URLSearchParams(); 
      body.append('username',this.pass); 
     this._http.post(url,body,{headers:header}).subscribe(
      res => console.log(res) 
     ); 
     } 
     view(){ 
     let body=new URLSearchParams(); 
      body.append('username',this.pass); 
     this._http.post("http://localhost:8000/demoApp/main2",body).subscribe(
      res => console.log(res) 
     ) 
     } 
     inval(){ 
     this._http.get("http://localhost:8000/demoApp/main3").subscribe(
      res => console.log(res) 
     ) 

爪哇主要的servlet部分

// TODO Auto-generated method stub 
    String s=request.getParameter("username"); 
    System.out.println(s); 
    HttpSession hs=request.getSession(true); 
    hs.setAttribute("s", s); 
    System.out.println("session created !! "+ hs.getAttribute("s")); 

爪哇MAIN2 servlet的部分

HttpSession hs=request.getSession(); 
    System.out.println("another page"+hs.getAttribute("s")); 

输出

enter image description here

+0

你怎么在这里做会话管理? –

+0

我感觉jsessionid cookie没有设置。你可以尝试直接从浏览器打到网址吗? – Sanj

回答

1

的问题是最有可能的是,2个请求没有出于某种原因,相同的会话ID。您可以使用:

HttpSession hs = request.getSession(true); 
hs.getId(); 

获取id和打印以查看它们是否相同。

This and this SO问题可能有助于解决如何维护会话的问题。

+0

我检查了身份证。你是对的,他们是不同的。我怎样才能解决这个问题 ? –

0

获取cookie(名称为JSESSIONID)然后使用它(在请求标头中)可能会有所帮助。

  1. 获取第一页的回复。用JS读取Cookie(名称为JSESSIONID)
  2. 使用它,你将调用请求(在头:饼干:“JSESSIONID =东西;”)...