扩展Struts

者:
Sunil Patil; loryliu
原文地址:
http://www.onjava.com/pub/a/onjava/2004/11/10/ExtendingStruts.html
中文地址:
http://www.matrix.org.cn/resource/article/43/43857_Struts.html

简介

我见过许多项目开发者实现自己专有的 MVC框架。这些开发者并不是因为想实现不同于Struts的某些功能,而是还没有意识到怎么去扩展Struts。通过开发自己的MVC框架,你可以掌控 全局,但同时这也意味着你必须付出很大的代价;在项目计划很紧的情况下也许根本就不可能实现。

Struts不但功能强大也易于扩展。你可以通过三种方式来扩展Struts:
  1. PlugIn:在应用启动或关闭时须执行某业务逻辑,创建你自己的PlugIn类
  2. RequestProcessor:在请求处理阶段一个特定点欲执行某业务逻辑,创建你自己的RequestProcessor。例如:你想继承RequestProcessor来检查用户登录及在执行每个请求时他是否有权限执行某个动作。
  3. ActionServlet:在应用启动或关闭或在请求处理阶段欲执行某业务逻辑,继承ActionServlet类。但是必须且只能在PligIn和RequestProcessor都不能满足你的需求时候用。

本文会列举一个简单的Struts应用来示范如何使用以上三种方式扩展Struts。在本文末尾资源区有每种方式的可下载样例源代码。Struts Validation 框架和 Tiles 框架是最成功两个的Struts扩展例子。

我是假设读者已经熟悉Struts框架并知道怎样使用它创建简单的应用。如想了解更多有关Struts的资料请参见资源区。

PlugIn

根据Struts文档,“PlugIn是一个须在应用启动和关闭时需被通知的模块定制资源或服务配置包”。这就是说,你可以创建一个类,它实现PlugIn的接口以便在应用启动和关闭时做你想要的事。

假 如创建了一个web应用,其中使用Hibernate做为持久化机制;当应用一启动,就需初始化Hinernate,这样在web应用接收到第一个请求 时,Hibernate已被配置完毕并待命。同时在应用关闭时要关闭Hibernate。跟着以下两步可以实现Hibernate PlugIn的需求。

1.创建一个实现PlugIn接口的类,如下:
  1. public class HibernatePlugIn implements PlugIn{
  2.     private String configFile;
  3.     // This method will be called at application shutdown time
  4.     public void destroy() {
  5.         System.out.println("Entering HibernatePlugIn.destroy()");
  6.         //Put hibernate cleanup code here
  7.         System.out.println("Exiting HibernatePlugIn.destroy()");
  8.     }
  9.     //This method will be called at application startup time
  10.     public void init(ActionServlet actionServlet, ModuleConfig config)throws ServletException {
  11.         System.out.println("Entering HibernatePlugIn.init()");
  12.         System.out.println("Value of init parameter"+getConfigFile());
  13.         System.out.println("Exiting HibernatePlugIn.init()");
  14.     }
  15.     public String getConfigFile() {
  16.         return name;
  17.     }
  18.     public void setConfigFile(String string) {
  19.         configFile = string;
  20.     }
  21. }
实现PlugIn接口的类必须是实现以下两个方法:
init() 和destroy().。在应用启动时init()被调用,关闭destroy()被调用。Struts允许你传入初始参数给你的PlugIn类;为了传 入参数你必须在PlugIn类里为每个参数创建一个类似JavaBean形式的setter方法。在HibernatePlugIn类里,欲传入 configFile的名字而不是在应用里将它硬编码进去。

2.在struts-condig.xml里面加入以下几行告知Struts这个新的PlugIn

  1. <struts-config>
  2.     ...
  3.     <!-- Message Resources -->
  4.     <message-resources parameter="sample1.resources.ApplicationResources"/>
  5.     <!-- Declare your plugins -->
  6.     <plug-in className="com.sample.util.HibernatePlugIn">
  7.         <set-property property="configFile" value="/hibernate.cfg.xml"/>
  8.     </plug-in>
  9. </struts-config>
ClassName属性是实现PlugIn接口类的全名。为每一个初始化传入PlugIn类的初始化参数增加一个<set- property>元素。在这个例子里,传入config文档的名称,所以增加了一个config文档路径的<set- property>元素。

Tiles和Validator框架都是利用PlugIn给初始化读入配置文件。另外两个你还可以在PlugIn类里做的事情是:

假如应用依赖于某配置文件,那么可以在PlugIn类里检查其可用性,假如配置文件不可用则抛出ServletException。这将导致ActionServlet不可用。

PlugIn接口的init()方法是你改变ModuleConfig方法的最后机会,ModuleConfig方法是描述基于Struts模型静态配置信息的集合。一旦PlugIn被处理完毕,Struts就会将ModuleCOnfig冻结起来。

请求是如何被处理的

ActionServlet 是Struts框架里唯一一个Servlet,它负责处理所有请求。它无论何时收到一个请求,都会首先试着为现有请求找到一个子应用。一旦子应用被找到, 它会为其生成一个RequestProcessor对象,并调用传入HttpServletRequest和HttpServletResponse为参 数的process()方法。

大部分请处理都是在RequestProcessor.process()发生的。Process()方法 是以模板方法(Template Method)的设计模式来实现的,其中有完成request处理的每个步骤的方法;所有这些方法都从process()方法顺序调用。例如,寻找当前请 求的ActionForm类和检查当前用户是否有权限执行action mapping都有几个单独的方法。这给我们提供了极大的弹性空间。Struts的RequestProcessor对每个请求处理步骤都提供了默认的实 现方法。这意味着,你可以重写你感兴趣的方法,而其余剩下的保留默认实现。例如,Struts默认调用request.isUserInRole()检查 用户是否有权限执行当前的ActionMapping,但如果你需要从数据库中查找,那么你要做的就是重写processRoles()方法,并根据用户 角色返回true 或 false。

首先我们看一下process()方法的默认实现方式,然后我将解释RequestProcessor类里的每个默认的方法,以便你决定要修改请求处理的哪一部分。

  1. public void process(HttpServletRequest request, HttpServletResponse response)
  2.         throws IOException, ServletException {
  3.         // Wrap multipart requests with a special wrapper
  4.         request = processMultipart(request);
  5.         // Identify the path component we will use to select a mapping
  6.         String path = processPath(request, response);
  7.         if (path == null) {
  8.             return;
  9.         }
  10.         if (log.isDebugEnabled()) {
  11.             log.debug("Processing a '" + request.getMethod() + "' for path '"
  12.                 + path + "'");
  13.         }
  14.         // Select a Locale for the current user if requested
  15.         processLocale(request, response);
  16.         // Set the content type and no-caching headers if requested
  17.         processContent(request, response);
  18.         processNoCache(request, response);
  19.         // General purpose preprocessing hook
  20.         if (!processPreprocess(request, response)) {
  21.             return;
  22.         }
  23.         this.processCachedMessages(request, response);
  24.         // Identify the mapping for this request
  25.         ActionMapping mapping = processMapping(request, response, path);
  26.         if (mapping == null) {
  27.             return;
  28.         }
  29.         // Check for any role required to perform this action
  30.         if (!processRoles(request, response, mapping)) {
  31.             return;
  32.         }
  33.         // Process any ActionForm bean related to this request
  34.         ActionForm form = processActionForm(request, response, mapping);
  35.         processPopulate(request, response, form, mapping);
  36.         // Validate any fields of the ActionForm bean, if applicable
  37.         try {
  38.             if (!processValidate(request, response, form, mapping)) {
  39.                 return;
  40.             }
  41.         } catch (InvalidCancelException e) {
  42.             ActionForward forward = processException(request, response, e, form, mapping);
  43.             processForwardConfig(request, response, forward);
  44.             return;
  45.         } catch (IOException e) {
  46.             throw e;
  47.         } catch (ServletException e) {
  48.             throw e;
  49.         }
  50.         // Process a forward or include specified by this mapping
  51.         if (!processForward(request, response, mapping)) {
  52.             return;
  53.         }
  54.         if (!processInclude(request, response, mapping)) {
  55.             return;
  56.         }
  57.         // Create or acquire the Action instance to process this request
  58.         Action action = processActionCreate(request, response, mapping);
  59.         if (action == null) {
  60.             return;
  61.         }
  62.         // Call the Action instance itself
  63.         ActionForward forward =
  64.             processActionPerform(request, response, action, form, mapping);
  65.         // Process the returned ActionForward instance
  66.         processForwardConfig(request, response, forward);
  67.     }
1、processMultipart(): 在这个方法中,Struts读取request以找出contentType是否为 multipart/form-data。假如是,则解析并将其打包成一个实现HttpServletRequest的包。当你成生一个放置数据的 HTML FORM时,request的contentType默认是application/x-www-form-urlencoded。但是如果你的form 的input类型是FILE-type允许用户上载文件,那么你必须把form的contentType改为multipart/form-data。如 这样做,你永远不能通过HttpServletRequest的getParameter()来读取用户提交的form值;你必须以 InputStream的形式读取request,然后解析它得到值。

2、processPath(): 在这个方法中,Struts将读取request的URI以判断用来得到ActionMapping元素的路径。

3、processLocale(): 在这个方法中,Struts将得到当前request的Locale;Locale假如被配置,将作为 org.apache.struts.action.LOCALE属性的值被存入HttpSession。这个方法的附作用是HttpSession会被 创建。假如你不想此事发生,可将在struts-config.xml 文件里ControllerConfig的local属性设置为false,如下:
 
 
  1. <controller>
  2.     <set-property property="locale" value="false"/>
  3. </controller>
4、processContent():通过调用response.setContentType()设置response的contentType。这个方法首先会试着的得到配置在struts-config.xml里的contentType。默认为text/html,重写方法如下:
 
 
  1. <controller>
  2.     <set-property property="contentType" value="text/plain"/>
  3. </controller>
5、processNoCache():Struts将为每个response的设置以下三个header,假如已在struts 的config.xml将配置为no-cache。
 
 
  1. response.setHeader("Pragma""No-cache");
  2. response.setHeader("Cache-Control""no-cache");
  3. response.setDateHeader("Expires"1);
假如你想设置为no-cache header,在struts-config.xml中加如以下几行
 
 
  1. <controller>
  2.     <set-property property="noCache" value="true"/>
  3. </controller>
6、processPreprocess():这是一个一般意义的预处理hook,其可被子类重写。在RequestProcessor里的实现什么都没有做,总是返回true。如此方法返回false会中断请求处理。

7、processMapping():这个方法会利用path信息找到ActionMapping对象。ActionMapping对象在struts-config.xml file文件里表示为<action>

 
 
  1. <action path="/newcontact" type="com.sample.NewContactAction" name="newContactForm" scope="request">
  2.     <forward name="sucess" path="/sucessPage.do"/>
  3.     <forward name="failure" path="/failurePage.do"/>
  4. </action>
ActionMapping元素包含了如Action类的名称及在请求中用到的ActionForm的信息,另外还有配置在当前ActionMapping的里的ActionForwards信息。
8、processRoles(): Struts的web 应用安全提供了一个认证机制。这就是说,一旦用户登录到容器,Struts的processRoles()方法通过调用request.isUserInRole()可以检查他是否有权限执行给定的ActionMapping。
  1. <action path="/addUser" roles="administrator"/>
假如你有一个AddUserAction,限制只有administrator权限的用户才能新添加用户。你所要做的就是在AddUserAction 的action元素里添加一个值为administrator的role属性。

9、processActionForm():每个ActionMapping都有一个与它关联的ActionForm类。struts在处理ActionMapping时,他会从<action>里name属性找到相关的ActionForm类的值。
  1. <form-bean name="newContactForm" type="org.apache.struts.action.DynaActionForm">
  2.     <form-property name="firstName" type="java.lang.String"/>
  3.     <form-property name="lastName" type="java.lang.String"/>
  4. </form-bean>
在这个例子里,首先会检查org.apache.struts.action.DynaActionForm类的对象是否在request 范围内。如是,则使用它,否则创建一个新的对象并在request范围内设置它。

10、processPopulate()::在这个方法里,Struts将匹配的request parameters值填入ActionForm类的实例变量中。

11、processValidate():Struts将调用ActionForm的validate()方法。假如validate()返回ActionErrors,Struts将用户转到由<action>里的input属性标示的页面。

12、processForward() and processInclude():在这两个方法里,Struts检查<action>元素的forward和include属性的值,假如有配置,则把forward和include 请求放在配置的页面内。
 
 
  1. <action forward="/Login.jsp" path="/loginInput"/>
  2. <action include="/Login.jsp" path="/loginInput"/>
你可以从他们的名字看出其不同之处。processForward()调用 RequestDispatcher.forward(),,processInclude()调用 RequestDispatcher.include()。假如你同时配置了orward 和include 属性,Struts总会调用forward,因为forward,是首先被处理的。

13、processActionCreate():这个方法从<action>的type属性得到Action类名,并创建返回它的实例。在这里例子中struts将创建一个com.sample.NewContactAction类的实例。

14、processActionPerform():这个方法调用Action 类的execute()方法,其中有你写入的业务逻辑。

15、processForwardConfig():Action类的execute()将会返回一个ActionForward类型的对象,指出哪一页面将展示给用户。因此Struts将为这个页面创建RequestDispatchet,然后再调用RequestDispatcher.forward()方法。

以上列出的方法解释了RequestProcessor在请求处理的每步默认实现及各个步骤执行的顺序。正如你所见,RequestProcessor很有 弹性,它允许你通过设置<controller>里的属性来配置它。例如,假如你的应用将生成XML内容而不是HTML,你可以通过设置 controller的某个属性来通知Struts。

创建你自己的RequestProcessor

从 以上内容我们已经明白了RequestProcessor的默认实现是怎样工作的,现在我将通过创建你自己的RequestProcessor.展示一个 怎样自定义RequestProcessor的例子。为了演示创建一个自定义RequestProcessor,我将修改例子实现以下连个业务需求:

我们要创建一个ContactImageAction类,它将生成images而不是一般的HTMl页面

在处理这个请求之前,将通过检查session里的userName属性来确认用户是否登录。假如此属性没有被找到,则将用户转到登录页面。


分两步来实现以上连个业务需求。
创建你自己的CustomRequestProcessor类,它将继承RequestProcessor类,如下:

  1. public class CustomRequestProcessor
  2.     extends RequestProcessor {
  3.         protected boolean processPreprocess (
  4.             HttpServletRequest request,
  5.             HttpServletResponse response) {
  6.             HttpSession session = request.getSession(false);
  7.         //If user is trying to access login page
  8.         // then don't check
  9.         if( request.getServletPath().equals("/loginInput.do")
  10.             || request.getServletPath().equals("/login.do") )
  11.             return true;
  12.         //Check if userName attribute is there is session.
  13.         //If so, it means user has allready logged in
  14.         if( session != null &&
  15.         session.getAttribute("userName") != null)
  16.             return true;
  17.         else{
  18.             try{
  19.                 //If no redirect user to login Page
  20.                 request.getRequestDispatcher 
  21.                     ("/Login.jsp").forward(request,response);
  22.             }catch(Exception ex){
  23.             }
  24.         }
  25.         return false;
  26.     }
  27.     protected void processContent(HttpServletRequest request,
  28.                 HttpServletResponse response) {
  29.             //Check if user is requesting ContactImageAction
  30.             // if yes then set image/gif as content type
  31.             if( request.getServletPath().equals("/contactimage.do")){
  32.                 response.setContentType("image/gif");
  33.                 return;
  34.             }
  35.         super.processContent(request, response);
  36.     }
  37. }
在CustomRequestProcessor 类的processPreprocess方法里,检查session的userName属性,假如没有找到,将用户转到登录页面。

对 于产生images作为ContactImageAction类的输出,必须要重写processContent方法。首先检查其request是否请求 /contactimage路径,如是则设置contentType为image/gif;否则为text/html。

加入以下几行代码到sruts-config.xml文件里的<action-mapping>后面,告知Struts ,CustomRequestProcessor应该被用作RequestProcessor类

  1. <controller>
  2.     <set-property  property="processorClass" value="com.sample.util.CustomRequestProcessor"/>
  3. </controller>
请注意,假如你只是很少生成contentType不是text/html输出的Action类,重写processContent()就没有问题。如不 是这种情况,你必须创建一个Struts子系统来处理生成image  Action的请求并设置contentType为image/gif

Title框架使用自己的RequestProcessor来装饰Struts生成的输出。

ActionServlet

假如你仔细研究Struts web应用的web.xml文件,它看上去像这样:
  1. <web-app >
  2.     <servlet>
  3.         <servlet-name>action=</servlet-name>
  4.         <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  5.         <!-- All your init-params go here-->
  6.     </servlet>
  7.     <servlet-mapping>
  8.         <servlet-name>action</servlet-name>
  9.         <url-pattern>*.do</url-pattern>
  10.     </servlet-mapping>
  11. </web-app >
这就是说,ActionServlet负责处理所有发向Struts的请求。你可以创建ActionServlet的一个子类,假如你想在应用启动和关闭 时或每次请求时做某些事情。但是你必须在继承ActionServlet类前创建PlugIn 或 RequestProcessor。在Servlet 1.1前,Title框架是基于继承ActionServlet类来装饰一个生成的response。但从1.1开始,就使用 TilesRequestProcessor类。

结论

开发你自己的MVC模型是一个很大的决心——你必须考虑开发和维护代码的时间和资源。Struts是一个功能强大且稳定的框架,你可以修改它以使其满足你大部分的业务需求。

另一方面,也不要轻易地决定扩展Struts。假如你在RequestProcessor里放入一些低效率的代码,这些代码将在每次请求时执行并大大地降低整个应用的效率。当然总有创建你自己的MVC框架比扩展Struts更好的情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值