0

I have specific requirement to do:

1) set session variable in request.getSession().setAttribute("globalVarable","game"); in a servlet

2) from a simple java method, i need to call above servlet, to get a session variable.

Example: I have Test servlet and Test1 servlet

public class Test extends HttpServlet {
  public void setUserName(HttpServletRequest req) {
      HttpSession session = req.getSession();
      session.setAttribute("globalPidValue", req.getUserPrincipal().getName());
  }  
}

public class Test1 extends HttpServlet{
    public String getSessionUser() {
        String globalUserName = PKISSO.userName;
        Test test = new Test();
        String bb = test.attribute("globalPidValue");
    }
}

I need to call Test servlet and get the global variable from the session

Can you please help me to get a session variable from a simple java method. Thanks in advance

user3145999
  • 21
  • 1
  • 5
  • I *think* that a session doesn't exist without a user, and a user only exists as they are related to requests that are sent to a server. Well, of course the session exists, but if you don't have a request, how do you get the session? The session itself is related to the cookie sent with the request, so you'd need the cookie itself to know what session to get. I'm not sure if that helps, but it may explain why you don't seem to be able to just "get a session variable" in the way you want (in a "simple java method"). – markspace Apr 21 '18 at 01:50
  • 1
    One thing that occurs to me would be for you to create your own Map, and store sessions in that map. Later you could retrieve the sessions based on some other criteria (user name perhaps?). But that's pretty much rolling your own solution. – markspace Apr 21 '18 at 01:52

1 Answers1

0

You need to make the question clearer.

This method will be "calling" the servlet in what sense? Do you mean that you want to send a request/response to it, as if you were a browser?

Please give some more details.

in a simple context you must receive the request as a parameter in the method

public void simpleMethod(HttpServletRequest request) {
    Object myAttribute = request.getSession.getAttribute("globalVarable");
    // got the session variable in myAttribute
}

see the documentation

Lucas Noetzold
  • 1,670
  • 1
  • 13
  • 29