ActionBeanContext也是Stripes應用程序的上下文。此上下文可以自定義,並可以包含任何你想要的。一些示例代碼:
package my.app;
public class CustomActionBeanContext extends ActionBeanContext {
public CustomActionBeanContext() {
super();
}
public MyObject getMyObject() {
return (MyObject) getServletContext().getAttribute(「myObject」);
}
// Alternative solution without ServletContextListner
private static MyObject2 myObject2;
static {
myObject2 = new MyObject2();
}
public MyObject2 getMyObject2() {
return myObject2;
}
}
要讓Stripes context factory知道你想要ActionBeanContext你需要一個init-PARAM添加到條紋過濾器在web.xml中使用自定義的:
<init-param>
<param-name>ActionBeanContext.Class</param-name>
<param-value>my.app.CustomActionBeanContext</param-value>
</init-param>
你可以
Public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("myObject", new MyObject());
}
例的ActionBean:
通過添加SerlvetContextListener初始化在服務器啓動你的對象
public class MyAction implements ActionBean {
private CustomActionBeanContext context;
@Override
public CustomActionBeanContext getContext() {
return context;
}
@Override
public void setContext(ActionBeanContext context) {
this.context = (CustomActionBeanContext) context;
}
@DefaultHandler
public Resolution view() {
MyObject myObject = getContext().getMyObject();
// doing something usefull with it..
}
}
另一種解決方案在我看來是一個優秀的解決方案,就是使用dependency injection框架將(singleton)對象注入到actionbeans中。看到這裏條紋配置示例:Injecting Stripes ActionBeans with Guice DI
難道你不只是問如何創建一個應用程序範圍的變量? (這是你通常在servlet的init()方法中做的)。這與實例變量完全不同。 – BalusC 2011-04-09 13:27:53
嗨,Balus的確,你是否在Stripes中放置了一個應用程序變量,我仍在搜索,不知道 – JBoy 2011-04-09 15:38:19