Domanda

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");
}
È stato utile?

Soluzione

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.

Altri suggerimenti

getSession() will return a new session if an existing session is not found. So you don't need to worry about this one ever returning null. Take note though, there's no get() method under HttpSession, it's getAttribute().

So you can do this:

public SearchFilters getFilters() {

    if(getSession().getAttribute("Filters") == null) {
         getSession().setAttribute("Filters", new SearchFilters());
    }

    return (SearchFilters) getSession().getAttribute("Filters");
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top