问题
I need to create an session scope variable exactly when a session is created, before any task is execute (because all my tasks need an init session scope variable to run). Because, session instance of HttpSession is automatically create by grails application when a session is created. Developer want to use session for store session variables just use 'session' instance. I can not find out where init session variable will be put. Hope that someone will help me. Thanks
回答1:
What you can do is have a HttpSessionListener that listens for session creation and session removal.
ou could change it to pull from the application context:
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.codehaus.groovy.grails.commons.ApplicationHolder;
public class MySessionListener implements HttpSessionListener {
private MyListener myListener;
public void sessionCreated(HttpSessionEvent event) {
String id = event.getSession().getId();
getMyListener().sessionCreated(id);
}
public void sessionDestroyed(HttpSessionEvent event) {
String id = event.getSession().getId();
getMyListener().sessionDestroyed(id);
}
public void setMyListener(MyListener myListener) {
this.myListener = myListener;
}
private synchronized MyListener getMyListener() {
if (myListener == null) {
myListener = (MyListener)ApplicationHolder.getApplication().getMainContext().getBean("myListener");
}
return myListener;
}
}
Reference Here : , if this doesnt
There is also other method ...let me know!
来源:https://stackoverflow.com/questions/22710031/create-session-variable-in-grails-when-session-is-created