2

I used java main servlet to create the session variable. But i am unable to access that session variable from java main2 servlet.

Front-end is Angular2 and back-end is java

Angular2 part

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

Java main servlet part

// 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"));

Java main2 servlet part

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

Output

enter image description here

2 Answers2

2

The problem is most likely that the 2 requests do not have the same session id for some reason. You can use:

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

To get the id and print to see if they are the same.

This and this SO questions may help address the issue of how to maintain the session.

Community
  • 1
  • 1
hack_on
  • 2,532
  • 4
  • 26
  • 30
0

Getting the cookie (with the name JSESSIONID) and then using it (in request headers) might help.

  1. Get first page's response. Use JS to read cookie (with name JSESSIONID)
  2. Use it in requests that you will call (in header: Cookie:"JSESSIONID=something;")...
user218046
  • 623
  • 6
  • 20