How to make session in Java?

15,002

As part of your request handling in a doGet or doPost method, here is how you can get session and use it to get and set variables.

//Obtain the session object, create a new session if doesn't exist
HttpSession session = request.getSession(true);

//set a string session attribute
session.setAttribute("MySessionVariable", "MySessionAtrValue");

//get a string sessson attribute
String strParam = session.getAttribute("MySessionVariable");


//get an integer sessioin attribute
Integer param = (Integer) session.getAttribute("MySessionVariable");

//set an integer session attribute
session.setAttribute("MySessionVariable", new Integer(param.intValue() + 1));
Share:
15,002
Kliver Max
Author by

Kliver Max

Updated on June 04, 2022

Comments

  • Kliver Max
    Kliver Max about 2 years

    I need make sessions in Java web application.
    I found that sesstion makes in servlet calass by method getSession().
    But i have a question about session parameters. For example i send to server login/pass and save it into session atributes. Okey. Next time i do something on client and send new params to server. Where i gonna send it? In another or same and i gonna use if else for handle params like this?

    enter image description here Another question: How to use params which i put in session(login/pass) in another classes?

    UPDATE

    I read about sessions. And have new question. How to use session params in enother class. I mean after login i send new params on server, read it in servlet and want to take a login/pass from session and send it with new params into another class.