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 上下文工厂知道您想要使用自定义 ActionBeanContext,您需要在 web.xml 中的 Stripes 过滤器中添加一个 init-param:
<init-param>
<param-name>ActionBeanContext.Class</param-name>
<param-value>my.app.CustomActionBeanContext</param-value>
</init-param>
您可以通过添加 SerlvetContextListener 在服务器启动时初始化对象:
Public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("myObject", new MyObject());
}
示例动作豆:
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..
}
}
另一种解决方案,在我看来是一种优越的解决方案,是使用依赖注入框架将(单例)对象注入到您的 actionbean 中。请参阅此处的 Stripes 配置示例:使用 Guice DI 注入 Stripes ActionBeans