Search code examples
javaservletsstruts2strutshttpsession

How to set the values in session?


If I'm getting empty session I need to setup some values to play the action class. So, here is the method

public SearchFilters getFilters() {
 return (SearchFilters) getSession().get("Filters");
}

I would like to check the session, if it's null, then I need to set the some values over here.

public SearchFilters getFilters() {
if(getSession().get("Filters").equals(null)){
---- //How to set the values and return ?
}
 return (SearchFilters) getSession().get("Filters");
}

Solution

  • Use the code:

    public SearchFilters getFilters() {
    if(getSession().get("Filters") == null){
      //How to set the values
      getSession().put("Filters", new Filters()); 
    }
    // and return.
     return (SearchFilters) getSession().get("Filters");
    }
    

    assumed you have injected the session into the action via implementing SessionAware.

    The value is a free hand object which contains no value, but you could create a constructor to it and pass the value directly.