我正在尝试找到一种在Stripes应用程序上下文中创建实例变量的方法。在使用手工编码的Servlet时,我将在Servlet的init()方法中执行的操作。问题在于,由于每次访问应用程序时都会创建一个ActionBean实例,因此会多次创建actionBean中的变量。我尝试过通过ActionBeanContext.getServletContext()调用ServletContext,但是没有办法访问init()方法并在其中编写一些代码。
你有什么意见建议?
发布于 2011-04-10 04:37:14
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,您需要在web.xml中的Stripes过滤器中添加一个初始化参数:
<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());
}示例ActionBean:
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..
}
}在我看来,另一种解决方案是使用 框架将actionbeans对象注入到actionbeans中。请参阅此处的条带配置示例:
发布于 2011-04-09 23:54:39
不是特定于Stripes的方式,而是使用标准的Servlet API来实现ServletContextListener,并在contextInitialized()方法中完成工作。如果您在web.xml中将其注册为<listener> (或者当您已经在使用JavaEE6时,使用@WebListener进行注释),那么它将在webapp启动时运行。
@Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("somename", new SomeObject());
}这样,它就可以在EL by ${somename}和所有action beans by ServletContext#getAttribute()中使用。
发布于 2011-06-06 01:16:17
@JBoy,您必须在web.xml中指定您的ServletContextListner实现,如下所示
<listner>
<listner-class>
www.test.com.MyListner
</listner-class>
</listner>感谢KDeveloper的建议。我也在寻找解决方案。我发现了他博客里的信息
我发现了另一种方法。为此,您必须继承"RuntimeConfiguration“类的子类
public class MyConfiguration extends RuntimeConfiguration {
@Override
public void init() {
getServletContext.setAttribute("myObject",new MyObject);
super.init();
}
}之后,在web.xml中指定上面的配置。
<init-param>
<param-name>Configuration.Class</param-name>
<param-value>www.test.com.MyConfiguration</param-value>
</init-param>您还必须像KDeveloper所说的那样,将ActionBeanContext子类化,以便在ActionBeans中获取对象
这是我的发现。我发现它起作用了。但我不知道它是否有副作用。如果它有,请评论..
https://stackoverflow.com/questions/5604976
复制相似问题