Struts Architecture

本文详细介绍了Struts2框架的工作流程,包括请求处理过程、核心组件如ActionProxy和ActionMapper的作用,以及配置文件的加载方式等。此外还讨论了如何自定义这些组件以满足特定需求。

1. Overview

 

In the diagram, an initial request goes to the Servlet container (such as Jetty or Resin) which is passed through a standard filter chain. The chain includes the (optional) ActionContextCleanUp filter, which is useful when integrating technologies such as SiteMesh Plugin. Next, the required FilterDispatcher is called, which in turn consults the ActionMapper to determine if the request should invoke an action.

 

If the ActionMapper determines that an Action should be invoked, the FilterDispatcher delegates control to the ActionProxy. The ActionProxy consults the framework Configuration Files manager (initialized from the struts.xml file). Next, the ActionProxy creates an ActionInvocation, which is responsible for the command pattern implementation. This includes invoking any Interceptors (the before clause) in advance of invoking the Action itself.

Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. The result is then executed, which often (but not always, as is the case for Action Chaining) involves a template written in JSP or FreeMarker to be rendered. While rendering, the templates can use the Struts Tags provided by the framework. Some of those components will work with the ActionMapper to render proper URLs for additional requests.

 

All objects in this architecture (Actions, Results, Interceptors, and so forth) are created by an ObjectFactory. This ObjectFactory is pluggable. We can provide our own ObjectFactory for any reason that requires knowing when objects in the framework are created. A popular ObjectFactory implementation uses Spring as provided by the Spring Plugin.

 

Interceptors are executed again (in reverse order, calling the after clause). Finally, the response returns through the filters configured in the web.xml. If the ActionContextCleanUp filter is present, the FilterDispatcher will not clean up the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present, the FilterDispatcher will cleanup all ThreadLocals.

 

 

All objects created by the framework are instantiated by the ObjectFactory. The ObjectFactory provides the means of integrating the framework with IoC containers like Spring, Pico, Plexus, and so forth.

 

2. ObjectFactory

Customized ObjectFactory must extend ObjectFactory or any of its descendants and have a default, no-argument constructor.

To register a customized ObjectFactory, add or edit an entry in struts.properties

 struts.objectFactory=foo.bar.MyCustomObjectFactory

where foo.bar.MyCustomObjectFactory is the custom object factory.

public class MyObjectFactory extends ObjectFactory {    .....}

3. ActionMapper

The ActionMapper interface provides a mapping between HTTP requests and action invocation requests and vice-versa.

When given an HttpServletRequest, the ActionMapper may return null if no action invocation request matches, or it may return an ActionMapping that describes an action invocation for the framework to try.

The ActionMapper is not required to guarantee that the ActionMapping returned be a real action or otherwise ensure a valid request. Accordingly, most ActionMappers do not need to consult the Struts configuration just to determine if a request should be mapped.

Just as requests can be mapped from HTTP to an action invocation, the opposite is true as well. However, because HTTP requests (when shown in HTTP responses) must be in String form, a String is returned rather than an actual request object.

DefaultActionMapper

By default, the DefaultActionMapper is used:

Default action mapper implementation, using the standard *.[ext] (where ext usually "action") pattern. The extension is looked up from the Struts configuration key struts.action.extension.

 

To help with dealing with buttons and other related requirements, this mapper (and other ActionMappers, we hope) has the ability to name a button with some predefined prefix and have that button name alter the execution behaviour. The four prefixes are:

 

  •  

     

  • Method prefix - method:default

     

     

  • Action prefix - action:dashboard

     

     

  • Redirect prefix - redirect:cancel.jsp

     

     

  • Redirect-action prefix - redirectAction:cancel

     

     

 

 

In addition to these four prefixes, this mapper also understands the action naming pattern of foo!bar in either the extension form (eg: foo!bar.action) or in the prefix form (eg: action:foo!bar). This syntax tells this mapper to map to the action named foo and the method bar.

In Struts 2.1.6 and earlier the Redirect Action prefix is "redirect-action", it was changed to "redirectAction" after the release of Struts 2.1.6

Method prefix

With method-prefix, instead of calling baz action's execute() method (by default if it isn't overriden in struts.xml to be something else), the baz action's anotherMethod() will be called. A very elegant way determine which button is clicked. Alternatively, one would have submit button set a particular value on the action when clicked, and the execute() method decides on what to do with the setted value depending on which button is clicked.

<s:form action="baz">    <s:textfield label="Enter your name" name="person.name"/>    <s:submit value="Create person"/>    <s:submit name="method:anotherMethod" value="Cancel"/></s:form>

Action prefix

With action-prefix, instead of executing baz action's execute() method (by default if it isn't overriden in struts.xml to be something else), the anotherAction action's execute() method (assuming again if it isn't overriden with something else in struts.xml) will be executed.

<s:form action="baz">    <s:textfield label="Enter your name" name="person.name"/>    <s:submit value="Create person"/>    <s:submit name="action:anotherAction" value="Cancel"/></s:form>

Redirect prefix

With redirect-prefix, instead of executing baz action's execute() method (by default it isn't overriden in struts.xml to be something else), it will get redirected to, in this case to www.google.com. Internally it uses ServletRedirectResult to do the task.

<s:form action="baz">    <s:textfield label="Enter your name" name="person.name"/>    <s:submit value="Create person"/>    <s:submit name="redirect:www.google.com" value="Cancel"/></s:form>

Redirect-action prefix

With redirect-action-prefix, instead of executing baz action's execute() method (by default it isn't overriden in struts.xml to be something else), it will get redirected to, in this case 'dashboard.action'. Internally it uses ServletRedirectResult to do the task and read off the extension from the struts.properties.

<s:form action="baz">    <s:textfield label="Enter your name" name="person.name"/>    <s:submit value="Create person"/>    <s:submit name="redirectAction:dashboard" value="Cancel"/></s:form>
In Struts 2.1.6 and earlier the Redirect Action prefix is "redirect-action", it was changed to "redirectAction" after the release of Struts 2.1.6

Custom ActionMapper

You can define your own ActionMapper by implementing org.apache.struts2.dispatcher.mapper.ActionMapper then configuring Struts 2 to use the new class in struts.xml

<bean type="org.apache.struts2.dispatcher.mapper.ActionMapper" name="mymapper" class="com.mycompany.myapp.MyActionMapper" /><constant name="struts.mapper.class" value="mymapper" />

Possible uses of the ActionMapper include defining your own, cleaner namespaces, such as URLs like /person/1, which would be similar to a request to /getPerson.action?personID=1 using the DefaultActionMapper.

CompositeActionMapper

A composite action mapper that is capable of delegating to a series of ActionMapper if the former failed to obtained a valid ActionMapping or uri.

It is configured through struts.properties.

For example, with the following entries in struts.properties

 

<bean type="org.apache.struts2.dispatcher.mapper.ActionMapper" name="struts"       class="org.apache.struts2.dispatcher.mapper.CompositeActionMapper" /><constant name="struts.mapper.composite"       value="org.apache.struts2.dispatcher.mapper.DefaultActionMapper,org.apache.struts2.dispatcher.mapper.RestfulActionMapper,org.apache.struts2.dispatcher.mapper.Restful2ActionMapper" />

When {@link CompositeActionMapper#getMapping(HttpServletRequest, ConfigurationManager)} or CompositeActionMapper#getUriFromActionMapping(ActionMapping) is invoked, CompositeActionMapper would go through these ActionMappers in sequence starting from ActionMapper identified by 'struts.mapper.composite.1', followed by 'struts.mapper.composite.2' and finally 'struts.mapper.composite.3' (in this case) until either one of the ActionMapper return a valid result (not null) or it runs out of ActionMapper in which case it will just return null for both {@link CompositeActionMapper#getMapping(HttpServletRequest, ConfigurationManager)} and CompositeActionMapper#getUriFromActionMapping(ActionMapping) methods.

 

For example with the following in struts-*.xml :-

   <bean type="org.apache.struts2.dispatcher.mapper.ActionMapper" name="struts"
       class="org.apache.struts2.dispatcher.mapper.CompositeActionMapper" />   
<constant name="struts.mapper.composite"
       value="org.apache.struts2.dispatcher.mapper.DefaultActionMapper,
foo.bar.MyActionMapper,foo.bar.MyAnotherActionMapper" />

CompositeActionMapper will be configured with 3 ActionMapper, namely "DefaultActionMapper", "MyActionMapper" and "MyAnotherActionMapper". CompositeActionMapper would consult each of them in order described above.

ActionMapper and ActionMapping objets

The ActionMapper fetches the ActionMapping object corresponding to a given request. Essentially, the ActionMapping is a data transfer object that collects together details such as the Action class and method to execute. The mapping is utilized by the Dispatcher and various user interface components. It is customizable through struts.mapper.class entry in struts.properties or struts.xml. Note that the value of this constant is the name of the bean of the new mapper.

Customize

Custom ActionMapper must implement ActionMapper interface and have a default constructor.
<bean type="org.apache.struts2.dispatcher.mapper.ActionMapper" name="mymapper" class="com.mycompany.myapp.MyActionMapper" />
<constant name="struts.mapper.class" value="mymapper" />
public class MyCustomActionMapper implements ActionMapper {  
public ActionMapping getMapping(HttpServletRequest request, 
                                  ConfigurationManager configManager) {    ....  }
   public String getUriFromActionMapping(ActionMapping mapping) {     ....  }}

See also: RestfulActionMapper

 

 

4. Action Proxy & ActionProxy Factory

 

The ActionProxy obtains the Action class and calls the appropriate method. By default, Actions are obtained through local instantiation, but an Action could also be obtained remotely if an alternative ActionProxy were provided.

An alternative ActionProxy can be configured through ActionProxyFactory. Typically, an ActionProxy will utilize the ActionInvocation to encapsulate the execution of a particular request.

The ActionInvocation determines how an Action is handled: Is it being intercepted, is there a PreResultListener acting on it.

Essentially, ActionProxy encapsulates how an Action can be obtained. ActionInvocation encapsulates how the Action is executed when a request is invoked.

Customization

ActionProxyFactory

 ActionProxyFactory.setFactory(new MyActionProxyFactory() {    ..... });

ActionProxy

 ActionProxyFactory.getFactory(new MyActionProxyFactory() {    
....  public ActionProxy createActionProxy(Configuration config,        
String namespace, String actionName, Map extraContext)            
throws Exception { 
       createActionProxy(config, namespace, actionName, extraContext, true);    }    
public ActionProxy createActionProxy(Configuration config,           
 String namespace, String actionName, Map extraContext,            
boolean executeResult, boolean cleanupContext)            
throws Exception {        ....   }   .... });

ActionInvocation

 ActionProxyFactory.getFactory(new MyActionProxyFactory() {    
...    
    public ActionInvocation createActionInvocation(ActionProxy actionProxy)                             
throws Exception {
          createActionInvocation(actionProxy, new LinkedHashMap());    }    
public ActionInvocation createActionInvocation(ActionProxy actionProxy, 
                            Map extraContext) throws Exception {
          createActionInvocation(actionProxy, extraContext, true);    
}    
public ActionInvocation createActionInvocation(ActionProxy actionProxy,
                             Map extraContext, boolean pushAction)
                             throws Exception {
          // do implementation of ActionInvocation herer
          .....    }
    ... });

5. Configuration Provider & Configuration

 

 

The ConfigurationProvider interface describes the framework's configuration. By default, the framework loads its configurations via an xml document by using the StrutsXmlConfigurationProvider. The provider can be configured through a Dispatcher's DispatcherListener.

Example

 static {   Dispatcher.addDispatcherListener(new DispatcherListener() {
     ....
     public void dispatcherInitialized(Dispatcher du) {
         ConfigurationManager confManager = du.getConfigurationManager();
         confManager.addConfigurationProvider( ... );     }     ....   }); 
}

 

C语言-光伏MPPT算法:电导增量法扰动观察法+自动全局搜索Plecs最大功率跟踪算法仿真内容概要:本文档主要介绍了一种基于C语言实现的光伏最大功率点跟踪(MPPT)算法,结合电导增量法与扰动观察法,并引入自动全局搜索策略,利用Plecs仿真工具对算法进行建模与仿真验证。文档重点阐述了两种经典MPPT算法的原理、优缺点及其在不同光照和温度条件下的动态响应特性,同时提出一种改进的复合控制策略以提升系统在复杂环境下的跟踪精度与稳定性。通过仿真结果对比分析,验证了所提方法在快速性和准确性方面的优势,适用于光伏发电系统的高效能量转换控制。; 适合人群:具备一定C语言编程基础和电力电子知识背景,从事光伏系统开发、嵌入式控制或新能源技术研发的工程师及高校研究人员;工作年限1-3年的初级至中级研发人员尤为适合。; 使用场景及目标:①掌握电导增量法与扰动观察法在实际光伏系统中的实现机制与切换逻辑;②学习如何在Plecs中搭建MPPT控制系统仿真模型;③实现自动全局搜索以避免传统算法陷入局部峰值问题,提升复杂工况下的最大功率追踪效率;④为光伏逆变器或太阳能充电控制器的算法开发提供技术参考与实现范例。; 阅读建议:建议读者结合文中提供的C语言算法逻辑与Plecs仿真模型同步学习,重点关注算法判断条件、步长调节策略及仿真参数设置。在理解基本原理的基础上,可通过修改光照强度、温度变化曲线等外部扰动因素,进一步测试算法鲁棒性,并尝试将其移植到实际嵌入式平台进行实验验证。
【无人机协同】动态环境下多无人机系统的协同路径规划与防撞研究(Matlab代码实现)​ 内容概要:本文围绕动态环境下多无人机系统的协同路径规划与防撞问题展开研究,提出基于Matlab的仿真代码实现方案。研究重点在于在复杂、动态环境中实现多无人机之间的高效协同飞行与避障,涵盖路径规划算法的设计与优化,确保无人机集群在执行任务过程中能够实时规避静态障碍物与动态冲突,保障飞行安全性与任务效率。文中结合智能优化算法,构建合理的成本目标函数(如路径长度、飞行高度、威胁规避、转弯角度等),并通过Matlab平台进行算法验证与仿真分析,展示多机协同的可行性与有效性。; 适合人群:具备一定Matlab编程基础,从事无人机控制、路径规划、智能优化算法研究的科研人员及研究生。; 使用场景及目标:①应用于灾害救援、军事侦察、区域巡检等多无人机协同任务场景;②目标是掌握多无人机系统在动态环境下的路径规划与防撞机制,提升协同作业能力与自主决策水平;③通过Matlab仿真深入理解协同算法的实现逻辑与参数调优方法。; 阅读建议:建议结合文中提供的Matlab代码进行实践操作,重点关注目标函数设计、避障策略实现与多机协同逻辑,配合仿真结果分析算法性能,进一步可尝试引入新型智能算法进行优化改进。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值