Using Struts to Develop Our Web Application

类别:.NET开发 点击:0 评论:0 推荐:

Author:Holyfair Chen
E-Mail:[email protected]

1. Introduction
 Struts is an open source of  webservice Framework host by ASF as a part of its Jakarta project.
 The primary architect and developer of the Struts framework is Craig R.McClanahan.He is also the
    primary architect of Tomcat 4.
     Notes:
     1) Struts is not only thread-safe but thread-dependent.
     2) ActionForm beans minimize subclass code and shorten subclass hierarchies.
     3) The Struts tag libraries provide general-purpose functionality.
     4) The Struts components are reusable by the application.
     5) The Struts localization strategies reduce the need for redundant JSPs.
     6) Struts is designed with an open architecture.
     7) Struts is lightweight.
     8) Struts is standards compliant.
     9) Struts is open source and well documented.
       10) Struts is model neutral.
 
2. Some Conception of webservies
 2.1 Serlvet
  Servlet 运行于Servlet容器,可以被Servlet容器动态加载控制服务器提供服务。
  API:HttpServletRequest,HttpSession和ServletContext分别提供了在request,session和application
  范围内的保存和读取共享数据的方法。
 2.2 JSP
  在传统HTML中加入Java程序片断(Scriptlet)和JSP标签就构成了JSP网页。
  JSP容器对一个JSP文件请求进行语法分析并生成Java Servlet源文件,然后不进行编译产生响应。
 2.3 共享数据的访问范围和生命周期
  page-->request-->session-->application
  (范围逐渐变大,具体参考其他资料)
 2.4 JavaBean
  符合特定规范的Java对象,定义了一些列属性并提供访问和设置这些属性的公共方法.
  (具体参照:http://java.sum.com/products/javabeans)
 2.5 Cookies
  Cookies and URL rewriting are two common ways to keep track of users between requests.
  Cookies 经过加密保存在客户端.
 2.6 CGI
  CGI uses standard operating system features, such as environment variables and standard input
  and output, to create a bridge, or gateway,between the web server and other applications on
  the host machine.
  The main drawback to CGI is that it must run a new copy of the CGI-aware program for each
  request.
 2.7 Web组件的三种关联关系
  * 请求转发(Forward)
  * URL重定向 (Redirect)
  * 包含 (Include)
 2.8 MVC(Model ,View and Controller)
  强制把应用程序的输入,处理和输出分开.
  例子:JSP(视图),Servlet(控制器),JavaBean(模型)
  
3. Exploring the Struts Architecture
 
      作为一个开放的框架,Struts允许使用JSP之外的技术构造View。在考虑改进Struts应用中的View技术时,人们首先想到的往往是用其他Servlet技术替代JSP,例如用XSLT或在Servlet管理之下的XSLT。

  下图描述了在Struts框架中应用JSP的情况。
  
   View由JSP定制标记库和JSP页面共同构造,其中ActionForm类是一种类似JavaBean的ValueObject对象,带有set和get方法,用来保存客户的状态。
    按照Struts的MVC概念,ActionForm位于View和Controller之间的中间地带。Struts提供了一组完备的专用标记,用来从
    JSP访问ActionForm里面的数据。
 
 2.1 Struts controller components
  [HyperLinks:ActionForward]
  To the application developer, a hyperlink is a path to some resource in the application.
  在配置文件中,我们可以如下定义一个forward:
   <forward name="welcome" path="/pages/index.jsp"/>
  我们可以在以后的Action中利用
   mapping.findForward("welcome")
  调用这个forward.
  在配置文件中定义的Forward可以是全局的,也可以是专署某个Action的
  
  [HTML forms:ActionForm]
  ActionForms are just JavaBeans with a couple of standard methods to manage the validation
  and revision cycle.
  它负责讲HTML中的表格转化成ActionForm数据类并可做检查传给Servlet来处理.
  我们可以如下自定义一个ActionForm:
  public final class LogonForm extends ActionForm
  {
   private String username = null;
   public String getUsername()
   {
    return (this.username);
   }
   public void setUsername(String username)
   {
    this.username = username;
   }
  }
  当然你还要在struts的配置文件中申明这个Form才可以用它,如:
   <form-bean name="articleForm" type="org.apache.artimus.struts.LogonForm"/>
  当一个Action要用到这个form时,在此Action的配置属性中加入name="articleForm"属性申明.
  
  [Custom actions]
  An HTML form uses an action parameter to tell the browser where to send the form’s
  data. The Struts framework supplies a corresponding Action class to receive such data.
  The framework automatically creates, populates, validates, and finally passes the
  appropriate ActionForm to the Action object. The Action can then get the data it needs
  directly from the ActionForm bean. Here’s an example:
   public final class LogonAction extends Action
   {
    public ActionForward perform(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    MyForm myForm = (MyForm) form;
    // ...
    return mapping.findForward("continue");
    }
   }
  Action也必须在Struts的配置文件中申明.
  如:
    <action path ="/update"
             name = "SRSForm"
      type  ="com.presentation.action.UpdateAction"
      scope  ="request"
      validate ="true"
    >
     <forward name="success" path="/srsPlay.do" redirect="false"/>
    </action>
  
   
  [ActionMappings]
  In a web application, every resource must be referred to through a Uniform
  Resource Identifier (URI). This includes HTML pages, JSP pages, and any custom
  actions. To give the custom Actions a URI, or path, the Struts framework provides
  an ActionMapping object. Like the ActionForwards and ActionForms, the mappings
  are usually defined in the XML configuration file:
   <action-mappings>
    <action
    path="/logonSubmit"
    type="app.LogonAction"
    name="logonForm"
    scope="request"
    validate="true"
    input="/pages/logon.jsp"/>
   </action-mappings>
  
  [ActionServlet] & [Localization]
   (略)
 
 2.2 Struts Control Flow
  下图很清楚的显示了Struts的控制过程:
  
  过程解析:
   检查和用户请求匹配的ActionMapping实例,如果不存在,就返回用户请求路径无效信息.
   如果ActionForm实例不存在,就创建一个ActionForm对象,把客户提交的表单数据保存到
    ActionForm中去.
   根据配置信息决定是否要进行表单验证.如果需要验证就调用ActionForm的validate()方法.
   如果ActionForm的validate方法返回null或返回一个不包含ActionMessage的ActionError
    对象,就表示成功.
   ActionServlet根据ActionMapping实例包含的映射信息决定是否将请求转发给哪个Action.
    如果相应的Action实例不存在,就先创建这个实例,然后调用Action的execute()方法
   Action的execute()方法返回一个ActionForward对象,ActionServlet再把客户请求发给
    ActionForward对象所指向的JSP组件
   ActionForward对象指向的JSP生成动态网页,返回给客户.

3. Configuring Struts Components
 Struts 的配置文件主要包括以下几个:
 web.xml:The web application deployment descriptor required by the Java Servlet specification.
         The servlet/JSP container uses this file to load and configure your application.
 build.xml: A file used by the Jakarta Ant build tool to compile and deploy your application.
     Using Ant is not a requirement, but it is a popular choice among Struts developers.
 struts-config.xml:The framework’s deployment descriptor. It is used to load and configure
     various  components used by the Struts framework.
 application.properties:This file provides the message resources for your Struts application.
     Like the build.xml file, it is not a strict requirement but is used
     by most Struts applications.
  
 
 3.1 web.xml
  例子解析:
  -----------------------------------------------------------------------------------
  <!-- 1 -->
  <?xml version="1.0" encoding="ISO-8859-1"?>
  <!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "
http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
  <web-app>
   <!-- 2 -->
   <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
     <param-name>application</param-name>
     <param-value>Application</param-value>
    </init-param>
    <init-param>
     <param-name>config</param-name>
     <param-value>/WEB-INF/conf/struts-config.xml</param-value>
    </init-param>
    <init-param>
     <param-name>debug</param-name>
     <param-value>2</param-value>
    </init-param>
    <init-param>
     <param-name>detail</param-name>
     <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
   </servlet>
   <!-- 3 -->
   <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
   </servlet-mapping>
   <!-- 4 -->
   <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <!-- 5 -->
   <taglib>
    <taglib-uri>/tags/struts-bean</taglib-uri>
    <taglib-location>/WEB-INF/lib/struts-bean.tld</taglib-location>
   </taglib>
   <taglib>
    <taglib-uri>/tags/struts-html</taglib-uri>
    <taglib-location>/WEB-INF/lib/struts-html.tld</taglib-location>
   </taglib>
   <taglib>
    <taglib-uri>/tags/struts-logic</taglib-uri>
    <taglib-location>/WEB-INF/lib/struts-logic.tld</taglib-location>
   </taglib>
  </web-app>
  -----------------------------------------------------------------------------------
  <1> 定义为web-app configuration问件.
  <2> 设置ActionServlet参数(只能load一个ActionServlet参数,否则引起冲突)
  <3> 定义Struts Request.
  <4> 设置welcome file.只能是实际存在的file,index.do形式的将不起作用.
      如果要用某个.do作为首页,则可构建一html包含其,例如下:
       ----------------------------------------------------------------------------
      <!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   <html>
    <head>
     <title>Struts Demo</title>
     <meta http-equiv="Refresh" content="0; URL=/CXdemo/login.do">
    </head>
    <body>
    </body>
   </html>
   ----------------------------------------------------------------------------
  <5> 设置taglib
  
 3.2 struts-config.xml
  例子解析:
  --------------------------------------------------------------------------------
  <struts-config>
     <!-- ======== global forwards Definitions ================================-->
    <global-forwards>
   <forward name="logoff" path="/Logoff.do"/>
    </global-forwards>
    <!-- ======== Form Bean Definitions =================================== -->
    <form-beans>
        <form-bean name="LoginForm" type="com.presentation.actionform.LoginForm"/>
    </form-beans>
     
    <!-- ========== Action Mapping Definitions ============================== -->
    <action-mappings>
      <!-- Say Hello! -->
      <action    path      = "/login"
                 type      = "com.presentation.action.LoginAction"
                 scope     = "request"
                 validate  = "true"
       >
       <forward name="logon" path="/Logon.do"/>
      </action>
    </action-mappings>
   
   
    <!-- ========== Message Resources Definitions =========================== -->
  
    <message-resources null="false" parameter="ApplicationResources" />
  
    <plug-in className="com.cappuccinonet.strutscx.util.StrutsCXPlugIn">
      <set-property property="config" value="/WEB-INF/strutscx-config.xml" />
    </plug-in>
   
  </struts-config>
  ----------------------------------------------------------------------------------------------
  此外还有全局Exception,Controller,data-sources等等定义.这里就不详细讲了.
  
 3.3 build.xml
  用于Struts项目创建时基于Ant开发的管理,具体可参见ant手册.
 
4.Installing the Struts core files
  All the stock files that you need to run Struts are provided in the Struts library
  distribution. These include several JARs, the tag library descriptors,
  DTDs, and standard XML configuration files. This set of stock files, combined
  with the four files you provide, create a complete core Struts configuration.
  Here’s the checklist:
    Download and unzip the Struts library distribution [ASF, Struts].
    Copy all the *.jar files to your application’s /WEB-INF/lib folder.
    Copy all the *.tld files to your /WEB-INF folder.
    Copy all the *.xml and *.dtd files to your /WEB-INF folder.
    Create your deployment descriptor (see 4.2).
    Create your Struts configuration file (see 4.4).
    Create your message resources bundle (see 4.5).
    Create your Ant build file (see 4.6).
  
5.总结
 关于Struts还有很多方面的东西.如:
  1) Struts模型组件方面
  2) Struts扩展方面
  3) Struts国际化方面
  4) Validator验证框架
  5) 复杂的异常处理
  6) Struts标签库
  7) Title框架
  8) 与EJB和SOAP Web服务
  9) Log
        10) StrutsTestCase测试
        11) 设计模式方面
        12) Struts各方面的各项扩展
 基于篇幅这里就不多录了.具体建议参考<Struts in Action>,不错的书.
 
  
  
  
  
  
  

 

 

 

 

 

 

 

 

 
 
 
 
 
============================================================================================================
============================================================================================================
参考资料:
 <Struts in Action>
 <精通Struts(基于MVC的Web 设计与开发)>
 

本文地址:http://com.8s8s.com/it/it43514.htm