0

I'm using a HttpSession session variable to store error/succes messages for various actions that my servlets are doing and I display those messages in jsp's when it requires.

But is it ok to create a new HttpSession object in each of the methods I use? Or should I create just a static one and hold there all my attributes? Thank you.

erasmus77
  • 327
  • 1
  • 5
  • 16
  • 2
    Hold on... Using JSP, you _do_ have access to the current HTTP session, why do you want to _create_ a new one? – fge Mar 04 '14 at 12:16
  • 1
    You can store data within your session by using session.setAttribute("key", "value"); Key is a string, value can be any object. You can use the HttpServletRequest in your servlet to get the session. In you JSP, you implicitely have access to your session by the "session" keyword. – Robert M. Mar 04 '14 at 12:24
  • It is not good to store your error/success message in session, because it will be available throughout your session till new session is not created. You need to remove your session attribute every time after you diaplayed it or used it. Better way to store it in request attribute as suggest by prit4fun – Yagnesh Agola Mar 04 '14 at 13:02
  • In jsp I only have a form, all the processing is done in a servlet. In order to store it in request I must use request dispatcher's forward but this means when the user refreshes the page the data gets submitted again. I do not want that. – erasmus77 Mar 04 '14 at 14:14

2 Answers2

3

If the purpose of that variable is only for success or error message, i would use request.setAttribute().

session.setAttribute() will keep that value through out the entire session, where as request.setAttribute() will keep that value available up to the life cycle of that request object.

prit4fun
  • 450
  • 1
  • 7
  • 15
2

You should not instantiate HttpSession yourself. To obtain HttpSession, use either HttpServletRequest#getSession() or HttpServletRequest#getSession(boolean). In JSP, you can use the session object directly.

chearius
  • 170
  • 6