How to set the values in session?

混江龙づ霸主 提交于 2019-12-06 09:10:59

问题


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");
}

回答1:


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 that is gotten by the getter method after implementing SessionAware. The value is free hand object, that contains no value, but you could create a constructor to it and pass the valued directly.




回答2:


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");
}


来源:https://stackoverflow.com/questions/17392001/how-to-set-the-values-in-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!