How can I expose an object to all of my Struts2 views?

岁酱吖の 提交于 2019-11-29 18:14:44
Andrea Ligios

Put your logic in a bean (eg. Configuration.java) that is then injected (through Spring DI, Java EE CDI, or whatever) in all the actions needing it, and exposed through a Getter.

But I would not underestimate the inheritance approach here, it's not as bad as you're describing it, 'cause you can build your inheritance tree adding specification while traversing it: one BaseAction, some Sub-BaseActions, some sub-sub... etc. Read more.

If you discover later that something you've put on a BaseAction is needed by sibling BaseActions, just move it one level up (in a parent BaseAction, up to the first one, common to everyone).

Write an interceptor that will intercept every action and add this interceptor to the custom interceptor stack. This stack you should make a default interceptor stack.

<interceptors>
  <interceptor name="myinterceptor" class="com.company.interceptor.MyInterceptor"/>
  <interceptor-stack name="customStack">
    <interceptor-ref name="myinterceptor"/>
    <interceptor-ref name="defaultStack"/>
  </interceptor-stack>
</interceptors>
<default-interceptor-ref name="customStack"/>

In the implementation of myinterceptor get bean from the application context and put it on the value stack. In every JSP you can access a value stack's object using OGNL.

Well, I think the inheritance solution fits well with your problem, all your controllers need these properties, so it is the best and most logical approach.

You could try the interceptor solution like Roman just told you, but I think interceptors are a little tricky to configure and the Struts2 error logs doesn't really help when something goes bad inside interceptors and you have a big application, moreover you would loose performance processing logic at the beggining of every action instead of using it with inheritance.

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