外文翻译:Struts框架介绍

简介: 外文翻译:Struts框架介绍

Introduction of struts  

1.   Talking the talk

This chapter explores the Struts framework in depth and highlights the benefits Struts can bring to your development efforts. We believe that once you can “talk the talk” of web architecture and design, you will be better equipped to use Struts with your own applications. With a sound overview of the Struts architecture in place, we outline the Struts control flow and the way it handles the request-response event cycle. A good understanding of this process makes it much easier to create applications that make the best use of the framework. Choosing a web application framework should not be a casual decision. Many people will use this book, and especially this chapter, as part of evaluating Struts for their project. Accordingly, we conclude this chapter with a candid look at the strengths and weaknesses of the Struts framework and address concerns regarding overall performance. Struts is designed for professional developers. To make informed decisions, professionals need to be aware of both a tool’s capabilities and its limitations.

2.  Why we need Struts

Today’s web applications are critical components of the corporate mission. As always, development teams need to build applications in record time, but they have to build them right and build them to last. Java web developers already have utilities for building presentation pages, such as Java Server Pages and Velocity templates. We also have mechanisms for handling databases—JDBC and Enterprise JavaBeans (EJB), for example. But what do we use to put these components together? We have the plumbing and the drywall … what else do we need?

2.1  Enter Struts

The centerpiece of Struts is an MVC-style Controller. The Struts Controller bridges the gap between Model and View. The framework also includes other missing pieces developers need to write scalable, leading-edge web applications. Struts is a collection of “invisible underpinnings” that help developers turn raw materials like databases and web pages into a coherent application.

2.2  Struts controller components

The Struts controller is a set of programmable components that allow developers to define exactly how their application interacts with the user. These components hide nasty, cumbersome implementation details behind logical names. Developers can program these details once, then go back to thinking in terms of what the program does rather than how it does it. Users interact with a web application through hyperlinks and HTML forms. The hyperlinks lead to pages that display data and other elements, such as text and images. The forms generally submit data to the application via some type of custom action. As shown in figure 2.2, Struts provides components that programmers can use to define the hyperlinks, forms, and custom actions that web applications use to interact with the user. We used these components to build a starter application in chapter 1. In chapter 3, we walk through using these components to build another simple application. Then, in chapter 4, we provide a detailed overview of configuring these components. Later chapters provide more detail about putting each component to use within your application. In part 4 we demonstrate using the components in the context of working applications. But, since this chapter is the architectural overview, let’s go ahead and introduce the major Struts components now.

2.3  Hyperlinks

To the application developer, a hyperlink is a path to some resource in the application. This may be a web page or a custom action. It may also include special parameters. In Struts, developers can define a hyperlink as an ActionForward. These objects have a logical name and a path property. This lets developers set the path and then refer to the ActionForward by name. ActionForwards are usually defined in an XML configuration file that Struts reads when the web application loads. Struts uses the XML definitions to create the Struts configuration, which includes a list of ActionForwards. The XML element that would create an ActionForward for a welcome hyperlink might look like this:

<forward

name="welcome"

path="/pages/index.jsp"/>

This element would create an ActionForm JavaBean with its name property set to welcome and its path property set to /pages/index.jsp. JSP pages and other components can then refer to the welcome forward. The Struts framework will look up the welcome ActionForward bean and retrieve the path to complete the hyperlink. This allows developers to change the destination of a link without changing all the components that refer to that link. In most web applications, details like this are hard coded into JSP and Java code, making changes difficult and prone to error. In a Struts application, these details can be changed throughout the application without touching a single page or Java class.

2.4  HTML forms

The web protocols, HTTP and HTML, provide a mechanism for submitting data from a form but leave receiving the data as an exercise for the developer. The Struts framework provides an ActionForm class, which is designed to handle input from an HTML form, validate the input, and redisplay the form to the user for correction (when needed), along with any corresponding prompts or messages. ActionForms are just JavaBeans with a couple of standard methods to manage the validation and revision cycle. Struts automatically matches the JavaBean properties with the attributes of the HTML controls. The developer defines the Action- Form class. Struts does the rest.

2.5  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");

}

}

An Action concludes by returning an ActionForward object to the controller. This allows the Action to choose a definition using logical names, like continue or cancel, rather than system paths. To ensure extensibility, the controller also passes the current request and response object. In practice, an Action can do anything a Java Servlet can do.

2.6  ActionServlet

The Struts ActionServlet works quietly behind the scenes, binding the other components together. Although it can be subclassed, most Struts 1.0 developers treat the ActionServlet as a blackbox: they configure it and leave it alone. For more about configuring Struts, see chapter 4.

In Struts 1.1, the ActionServlet is easier to extend. Chapter 9 covers the new extension points and configuration options for the Struts 1.1 ActionServlet.

2.7  Localization

Web applications also interact with users through prompts and messages. The Struts components have localization features built in so that applications can be written for an international audience. We refer to the localization featuresthroughout the book.

2.8  Developing a web application with Struts

To build a web application with Struts, developers will define the hyperlinks they need as ActionForwards, the HTML forms they need as ActionForms, and whatever custom server-side actions they need as Action classes.Developers who need to access EJB or JDBC databases can do so by way of the Action object. This way, the presentation page does not need to interact with the Model layer. The Struts Action object will collect whatever data a View may need and then forward it to the presentation page. Struts provides a JSP tag library for use with JSP pages that simplifies writing HTML forms and accessing other data that an Action may forward. Other presentation devices, such as Velocity templates, can also access the Struts framework to create dynamic web pages.

3.  Why we need frameworks

In chapter 1, we introduced application frameworks and briefly discussed why frameworks are important. But to really understand a solution, you need to appreciate the problem. Developing for the web, while rewarding, brings its own set of challenges. Let’s take a quick look at what makes web development so challenging.

3.1  The Web—a never-ending kluge

Web developers are hampered by a double web whammy. First, we are expected to use web browsers for clients. Second, we must use the web protocol to communicate. Web browsers communicate via Hypertext Transmission Protocol (HTTP) and display pages created with Hypertext Markup Language (HTML). A web browser sends out the HTTP request and renders the HTML it receives in response. This is an excellent platform for serving prewritten pages that rarely change. But most of us are writing dynamic applications with pages that are customized for each user. While there are some handy “hooks” for dynamic features, web applications go against the HTTP/HTML grain. Sadly, the situation is not going to change any time soon. Web developers must see these shortcomings as challenges to overcome. Since there are so many obstacles to writing robust web applications, using a framework is vital, lest your application become an endless series of workarounds and kluges. The challenges we face when developing web applications are great. But so are the rewards. The duo of the HTTP protocol and the HTML client makes web applications accessible to people the world over. No other platform has ever been able  to make that claim.

3.2  The servlet solution

As mentioned in chapter 1, the Java Servlet platform [Sun, JST] acts like a base framework to provide Java web applications with a number of important capabilities. The servlet class provides a base interface for handling HTTP requests and the ensuing response. It builds on HTTP to provide a “session” context to help track users in the application. It provides other contexts to help applications pass data to the browsers or to other servlets in the application. Java web applications also have uniform access to basic security features that would otherwise be managed differently by different HTTP servers. To put this all together, the servlet specification describes a container to manage the servlets. The container may also provide other services, such as a handler for JSP. A servlet container can include its own web server or simply act as an adjunct to an existing web server.

For database access, Java applications have another common framework at their disposal: JDBC. Developers can write to a standard SQL interface while an adapter takes care of the hoary details. This makes it easier to change database vendors without rewriting the source code.

For high-performance applications that access database systems on remote servers, web developers can use the Enterprise JavaBean platform. Most Java application frameworks, including Struts, can be used with EJB when they are needed. Overall, this makes web applications based on Java servlets very portable and relatively easy to write and maintain. Servlet and JSP have made a real difference in the way we write applications. Java web application frameworks like Struts build on the servlet platform and try to provide developers with a seamless, kluge-free environment.

3.3  Servlet frameworks

Most, if not all, Java web frameworks use the Sun Servlet platform as a foundation. These frameworks bundle one or more prewritten servlets that you can plug into your application. A framework will also include a hierarchy of classes that you can implement or extend within your own application.In general, the focus of a web application framework is to help get the data you need out of a browser and into a programming structure, where your application can use it—or out of a programming structure and into a browser, where your user can see it.Some frameworks, such as Turbine [ASF, Turbine], also provide helper classes for working with JDBC databases. Other frameworks, like Struts, are model neutral.

They don’t hinder database access but neither do they help. Even other frameworks, like dbForms [dbForms], specialize in database access and leave other tasks as an exercise for the developer (or to another framework, like Struts).

3.4  The whitebox-blackbox continuum

Frameworks are sometimes categorized into a continuum with poles labeled whitebox and blackbox [Fayad]. Whitebox frameworks rely heavily on object-oriented language features such as inheritance and dynamic binding. Blackbox frameworks tend to define interfaces for pluggable components and then provide base starter components based on those interfaces. The interface and base components will often provide hotspot methods that can be used as is or overridden to provide special behavior. Like many real-life frameworks, Struts uses a mix of whitebox and blackbox techniques. But overall, the framework would be placed toward the blackbox end of the continuum. Blackbox frameworks often rely strongly on design patterns. Struts is no exception. In fact, design patterns are often used to provide higher-level descriptions of frameworks [Johnson]. In keeping with this trend, let’s introduce the design patterns and show how they are used within the Struts framework.

4.  The evolution of MVC

The MVC example in Design Patterns extols its use of the notify/subscribe protocol and the Observer pattern. The essentials of the example are that a system needs to display several different views of the same data, such as a bar chart, piechart, and spreadsheet. This is an excellent justification for compartmentalizing applications, and the example has been often repeated.

4.1  The rise of Model 2

JavaServer Pages are intended make dynamic web pages easier to write. JSPs were first introduced as an alternative to servlets, as well as to Microsoft’s Active Server Pages. Developers were offered the power of servlets as easy-to-create server pages. But with great power comes great responsibility. Many teams found that if they were not careful, a project could easily collapse under the weight of hopelessly intertwined pages. Advanced features required the use of complex scriptlets. Butscriptlets are difficult to reuse—unless you’re pasting the code from page to page.

Utility pages can be included, but they are difficult to keep organized and make for some very ugly “source” trees. Something was wrong with this picture. Many developers soon realized that JSPs and servlets could be used together to deploy web applications. The servlets could cope with the control flow; the JSPs could focus on the nasty task of writing HTML. In due course, using JSPs and servlets together became known as Model 2 (using JSPs alone was referred to as Model 1). Of course, there is nothing new under the Sun... and many have been quick to point out that JSP’s Model 2 resembles the classic Model-View-Controller architecture.In some circles, it is now commonplace to use the terms Model 2 and MVC interchangeably, although some dispute whether an application can be MVC and not support the classic Observer notification pattern. Model-View-Controller without the notification pattern is sometimes called MVC2 or Web MVC.

4.2  Application layers—decoupling the view

Many architects of distributed systems, including web applications, wince at the idea of the view making a state query. Most often, remote applications are designed around the Layers pattern [POSA]. Essentially, the Layers pattern says that classes may interact with classes in their own layer or classes in an adjacent layer. In a complex application, this keeps dependencies from growing exponentially as components are added. Layering is a core pattern in the design of remote applications.From an MVC context, introducing the Layers pattern puts the responsibility for both state changes and state queries onto the Controller along with any change notifications. The major responsibilities of each component are unchanged. The flow changes slightly in that any state query or change notification must pass through the Controller. Another difference is that when the View, or presentation layer, renders dynamic content, it uses data passed by the Controller rather than data returned directly by the Model. This change decouples the View from the Model, allowing the Controller to select both the data and View that displays the data.

5.  Struts control flow

Since web applications are dynamic, it’s difficult to represent the “One True Control Flow.” Depending on the circumstances, a lot of different things can happen in different ways—especially in web applications. But there is still a general order to things that we can review here.

If you are new to Struts, or application frameworks, or even web applications, this process may seem hard to follow at first. The various problems it is trying to solve may not be evident. We’ll be covering those in detail throughout the book. Here, we try to take a look at the forest before introducing the trees. As you read through the book, we recommend that you revisit this section occasionally to see how the pieces fit into the big picture.

5.1  Is Struts performant

After a detailed description of the Struts process, you might wonder how long all this is going to take. In general, Struts should improve the performance of most properly designed web applications. In this section, we examine a few specific design points that contribute to the framework’s efficiency. Struts is not only thread-safe but thread-dependent. A lightweight Action object, rather than an individual servlet, handles the response to a request. Struts instantiates each Action class once and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best、possible throughput. A properly designed application will exploit this further by routing related operations through a single Action.

ActionForm beans minimize subclass code and shorten subclass hierarchies. A key point in the Struts framework is automatically populating any ActionForm bean from any request. Without this component, custom code may have to be written and instantiated to populate each class of bean. The careful use of reflection saves resources, which are always finite, allowing them to be put to better use.

The Struts tag libraries provide general-purpose functionality. The bean and logic taglibs bundled with Struts can meet most JSP tag needs. They reduce or even eliminate the need to write and instantiate additional tags. The JSP specification includes tag reuse within a JSP. Using the same general-purpose tag three times is more performant than using three different tags. The Struts components are reusable by the application. Utilities bundled with the framework have uses throughout most applications. The BeanUtil.populate method is a good example. This method is used to populate form beans from an HTTP request but can also be used to populate any bean from any type of map. Reusing components reduces overhead and conserves resources.

The Struts localization strategies reduce the need for redundant JSPs. By allowing localized messages to be retrieved at runtime, internationalized applications can provide a single page where one page for each language would otherwise be needed. Meanwhile, the same messaging system is also used to handle error messages, providing dual use of the same objects. Struts is designed with an open architecture. Struts components are designed so that they can be subclassed by an application to provide additional functionality. This allows developers to extend existing classes rather than add the overhead of creating and integrating new classes. Also, Struts shares its resources with the application. This allows developers to leverage existing components, so they do not have to write and instantiate their own. Struts is lightweight. Similar frameworks may provide hundreds of classes or tags and dozens of packages. The entire Struts framework is made up of five tag libraries and five core packages.

Struts is standards compliant. Many containers are designed to perform best when using standard components—JSP and JavaBeans, for example. Struts is open source and well documented. This means developers can easily examine the code to identify and resolve any potential bottlenecks.

Struts is model neutral. Since Struts does not make any assumptions about the backend model, an application can implement the Model layer in the most efficient way possible. Struts Actions can call a set of helper classes to access needed data. Once the data is retrieved, Struts’ reliance on JavaBeans makes it easy to retain value objects and reduce the number of calls to the Model layer.

Struts简介

1  探讨Struts

本章深入探讨Struts 框架,以及它能给你的应用开发所带来的诸多好处。我们相信,一旦你也能“随便谈谈”web 架构和设计,你就可以很好的在你的应用中使用Struts。为了能对Struts 架构有个充分的全面印象,我们将总体介绍Struts 的控制流和它处理请求响应事件循环的方式。只有彻底理解这个处理原理才能最好的在应用中使用这个框架。选择一个web 应用框架不应该是个漫不经心的决定。很多人都可以使用这本书,特别是用这章的内容,来评价Struts 是否适合它们的项目。因此,我们在这章的最后部分将有一个关于Struts 优缺点的客观评价,并阐明其总体性能。Struts 设计来针对专业开发人员。为做出正确的决策,专业人员应该知晓工具的能力和限制。

2  为什么我们需要Struts

今天的web 应用基本上都是代表共同理念的关键组件。通常,开发团队需要在有限的时间里创建应用,然后它们不得不正确的构建,并能持续构建它。Java web 开发人员已经有一些工具可用来建立表现层,比如JavaServer Pages 和Velocity模板。也有一些机制来处理数据库—如JDBC 和Enterprise JavaBean (EJB)。但我们用什么来将它们集合在一起?我们已经有了型材和砖墙…还缺什么呢?

2.1 进入Struts

Struts 的核心是一个MVC 风格的控制器。Struts 控制器搭起了Model 和View 之间的桥梁。框架也包括开发人员想用来开发可伸缩的、先进的应用系统的其他组件。Struts 是一个“隐藏支柱”的集合,帮助开发人员将分散的材料,如数据库和页面,结合成一个整体的应用系统。

2.2 Struts控制器组件

Struts 控制器组件是一个可编程的组件集,允许开发人员定义它们的应用如何准确地和用户进行交互。这些组件在逻辑名称后面隐藏了令人讨厌的、繁琐的实现细节。开发人员可以一次性编写这些实现细节,然后转头考虑它们的应用应该做什么,而不是考虑应用应该如何做。用户通过超链接和HTML form 与Web 应用程序进行交互。超链接引导页面显示数据和其他内容,如文本和图像。表单通常通过一些定制动作向应用提交数据。Struts 提供了开发人员可用来定义超链接,表单,和定制动作这些交互的相关组件。我们已经使用这些组件在第1 章创建了一个入门程序。第3 章,我们还要用它们来创建另一个程序。然后,在第4 章,我们将讨论这些组件的详细配置。随后的章节,将详细讨论如何将每个组件以及如何用在你的程序之中。在第4 章,我们将展示如何在运行的程序上下文中使用这些组件。但是,因为这一章是架构性的总体介绍,所以我们继续介绍Struts的主要部件。

2.3  超链接

对应用开发人员来说,超链接是指向应用中某些资源的路径。这些资源可能是web 页面,或者是定制动作。超链接中也可以包含特殊的参数。在Struts 中,开发人员可以将超链接定义为一个ActionForward。这些对象都有个逻辑名称和一个path 属性。这使得开发人员可以设置path,然后通过名称来引用ActionForward。ActionForward 通常在一个XML 文件中定义,这个配置文件在Struts 启动时载入。Struts 使用XML 定义来创建Struts 配置,包括一个ActionForward的列表。可用来创建到欢迎页面链接的ActionForward 对象XML 元素看起来可能像:

<forward

name="welcome"

path="/pages/index.jsp"/>

这个元素事实上是创建了一个ActionForward JavaBean ,其name 属性设置为welcome,path 属性设置为/pages/index.jsp。JSP 页面和其它组件就可以引用这里定义的welcome 转发。Struts 框架将查找welcomeActionForward bean 并获取其path 属性以完成这个超链接。这样开发人员可以改变链接的目标而不用

变所有引用该链接的相关件。在很多Web 应用中,象这样的细节被硬编码到JSP 或Java code 中,使维护变得困难并且容易发生错误。在Struts 应用中,这些细节可以通过应用配置来改变,而不用触及到具体的页面和Java 类。

2.4  HTML表单

Web 协议,即HTTP 和HTML,提供了一个从表单中提交数据的机制,但却把数据的接收作为一个难题留给了开发人员。为此,Struts 框架提供了ActionForm 类。ActionForm设计来就是处理来自HTML 表单的输入:校验输入,重新显示表单以供用户进行修订(如果需要),以及伴随着相应的提示和错误信息。ActionForm 其实是具有一些用来来管理校验和修订循环的标准方法的JavaBean。Struts 自动匹配JavaBean 属性和HTML 表单控件的属性。开发者只需定义ActionForm 类,余下的就交给Struts 。

2.5  Custom actions

定制动作 HTML 表单使用action 参数来告诉浏览器将数据送到何处。Struts 框架提供相应的Action 来接收数据。框架会自动创建、组装、校验和最后处理Action 对象所对应的ActionForm。这样,Action 就可以直接从ActionForm bean 取得它需要的数据。比如下例:

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 根据返回到控制器的ActionForward 对象作出控制流的决定。这允许Action 选择一个逻辑名称,比如continue 或者cancel,而不是具体的系统路径。

为保证可扩展性,控制器也传递当前的请求和响应对象。实际上,Action 可以做所有JavaServlet 可以做的事情。ActionMapping在一个web 应用中,每个资源都必须通过URI 来进行引用。资源束括HTML 页面,JSP页面,和定制动作。为了给定制动作一个URI,或者说路径,Struts 框架提供了一个ActionMapping 对象。象ActionForward 和ActionForm 一样, ActionMapping 通常也在XML 配置文件中定义:

<action-mappings>

<action path="/logonSubmit"

type="app.LogonAction"

name="logonForm"

scope="request"

validate="true"

input="/pages/logon.jsp" />

</action-mappings>

这也允许将同一个Action 对象定义为不同的ActionMapping。例如,其中一个映射要求校验而另一个映射不要求校验。

2.6  ActionServlet

Struts ActionServlet 完全在幕后工作,它将其他组件绑定在一起。虽然它也可以子类化,但大多数Struts 1.0 的开发人员将ActionServlet 处理为一个黑盒:他们只是配置它,然后让它自己工作。在Struts 1.1 中,ActionServlet 是比较易于扩展的。第9 章将讨论Struts 1.1 ActionServlet新的扩展点和配置选项。

2.7  本地化

Web 应用也通过各种提示和信息与用户进行交互。Struts 组件均有内建的本地化特征,以便Struts 应用可以为国际化用户使用。我们在此书中贯穿使用本地化特征。

2.8  用Struts开发Web应用

要使用Struts 开发web 应用,开发人员将需要的超链接定义ActionForward,HTML 表单定义为ActionForm,定制的服务器端动作定义为Action 类。需要访问JDBC 和EJB 的开发人员也可通过Action 对象进行他们的工作。这样,表现层不需要和Model 层打交道。。Struts Action 对象将收集View 需要的数据,然后将它们转发到表现页面。Struts 提供JSP 标记库,它们将和JSP 页面一起使用,简化HTML 表单和访问Action 要转发的其它数据。其它表现机制,比如Velocity templates, 也可用来访问Struts 框架,以创建动态的web 页。

3  为什么需要框架

第1 章,我们介绍了应用框架,简短讨论了为什么框架很重要。但为了真正理解一个解决方案,我们需要了解问题所在。为web 开发应用虽然是值得的,但也要迎接各种挑战。让我们快速看看是什么使web 开发富有挑战。

3.1 Web—永无休止的修补

Web 开发者受到两种web 缺陷的影响。首先,我们希望使用浏览器作为客户端。其次,我们必须使用web 协议进行通讯。Web 浏览器通过HTTP 协议通信,并用HTML 显示页面。Web 浏览器发送HTTP 请求,并渲染和显示它收到的响应。在处理很少改变的预先编好的页面时,这是个很好的平台。但我们大多都是编写动态程序,页面针对不同的用户是不同的。虽然有一些现成的动态特征的手段,web 仍然受到HTTP/HTML 的制约。很不幸,这种状况现在并没有些许改变。Web 开发人员在想战胜挑战时必须首先看到这些缺陷。因为这对编写强壮的Web 应用有太多障碍,使用框架便显得至关重要,免得你的应用陷入无休止的工作和改进之中。在开发Web 应用时我们面临的挑战是很巨大的。但同时也是值得的。HTTP 协议和HTML客户端使所有的人都可以访问你的应用。没有其他哪个平台能声称这样。

3.2 Servlet 解决方案

如第一章所述,Java Servlet 平台[Sun, JST] 扮演了一个基本框架,为Java web 应用提供了大量的能力。Servlet 提供了一个处理HTTP 请求和确保响应的基本接口。它在HTTP 之上构建了一个“会话” 上下文,帮助跟踪应用程序的用户。当然它也提供其他的上下文,帮助应用传输数据到浏览器或者应用中的其他servlet。Java web 应用也具有对基本安全特性的统一访问,而这些安全特性在不同的服务器上的管理是不一样的。为了将这些内容集成在一起,Servlet 规范引入了一个容器来管理它们。容器也可以提供其他服务,比如作为一个JSP 的处理器。Servlet 容器可以包含它自己的web server,也可以简单的作为一个现有服务器的附属组件。对数据库访问,Java 应用在其建议中有另外一个通用的框架:JDBC。开发者可以编写标准的SQL 接口,而将烦人的细节留给适配器来处理。这使得可以很容易的改变数据库厂商,而不用重写源代码。为了取得远程服务器的高性能数据库访问,web 开发人员可以使用EJB 平台。大多数Java应用框架,包括Struts, 都可以和EJB 一起使用。

总之,这使得基于Servlet 的web 应用非常轻便,并相对易于编写和维护。Servlet 和JSP在编写应用中扮演了完全不同的角色。象Strtus 这样的Java web 应用框架就构架于Servlet 之上,给开发者提供一个无缝的集成环境。

3.3 Servlet 框架

大多数,不是全部,Java web 框架使用Sun Servlet 平台为基础。这些框架都绑定一些预制的servlet,你可以插入到你的应用中去。框架本身也包括一个类层次结构,这些类(或接口)你可以在你的应用中实现或者扩展。通常, 应用框架的目标是帮助你将你需要的数据从浏览器发出,进入到编程结构之中,这样你的应用就可以使用它—或者从编程结构中发出,进入到浏览器之中,这样你就可以看到。一些框架,如Turbine [ASF, Turbine],也提供helper 类来使用JDBC 数据库。其他框架,如Struts,则是模型中立的。它们既不阻碍数据库访问,也没有提供帮助。而某些框架, 如dbForms [dbForms],则专注于数据库访问,而将其它任务留给开发人员或者其他框架。

3.4 黑盒-白盒统一体

框架有时分为两极标有白盒和黑盒的统一体[Fayad]。白盒框架严重依赖于面向对象的语言的特征,如继承和动态绑定。黑盒框架则注重定义可插入组件的接口,然后基于这些接口提供基本的起始组件。接口和基本组件通常提供热点(hotspot)方法,这个方法可以直接使用或者重写后提供特别的行为。像许多正在使用的框架,Struts 使用混合的黑盒和白盒技术。但总体上,框架将偏向统一体的黑盒一端。黑盒框架通常依赖于设计模式。事实上,设计模式通常被用来作为框架的总体描述[Johnson]。为保持这个趋势,我们先介绍一下设计模式,以及它们是如何用在Struts框架之中。

4   MVC的演化

Smalltalk MVC 方案使用观察者通知模式。在这种模式下,每个视图注册为一个模型数据的观察者。然后模型可以通过发送消息给所有这册观察者,通知它们相关的改变。其为Smalltalk MVC 框架已经通用化了,他也可以将它应用到其他平台上面。

4.1 Model 2的出现

JSP 的意图是使创建动态页面更容易。JSP 首先是作为servlet 的替代引入的,还有就是MS的ASP。Servlet 的强大功能当作易于创建服务器页面的工具提供给开发者。但强大的功能伴随着巨大的责任。很多团队发现,如果他们一不小心,他们的项目就会因为纠缠如麻的页面变的容易崩溃。进一步的特性需要使用复杂的脚本程序。但脚本程序是非常难于重用的—除非你在页面间把代码“拷贝粘贴”。工具页面也可以包括进来,但它们很难被组织在一起,并且造成非常丑陋的“资源”树。有些东西会出错。很多开发人员很快意识到,JSP 和servlet 可以一起使用来部署web 应用。Servlet 可以应付控制流,而JSP 则可专注于讨厌的编写HTML 的任务。在这种情况下,结合使用JSP和servlet 开始被称为Model 2 (单独使用JSP 称为Model 1)。当然,从Sun 那里仍然没什么新东西... 而且很多人很快指出JSP Model 2 类似于经典的Model-View-Controller 架构。在很多场合,现在交互使用Model 2 和MVC 这两个词已经很平常了,虽然还有一些争论,即一个应用是否是MVC,以及是否支持经典的观察者通知模式。没有观察者通知的Model-View-Controller 有时被称为MVC2 或Web MVC。

4.2 应用层—视图之间的去耦合

许多分布式系统架构,包括web 应用,在视图进行状态查询的概念时退缩了。绝大多数情况下,远程应用是按层模式[POSA]设计的。基本上,层模式下,层内的对象可以和同一层或者相邻层的对象进行通信。在一个复杂应用中,这可以在添加组件时,防止依赖关系呈指数增长。在设计远程应用时,分层是一个核心模式。从MVC 上下文中,引入层模式将状态改变和状态查询的职责加于控制器之上,并伴随着改变通知。每个组件的主要职责并没有改变。流程有轻微改变,即查询状态和改变通知都必须通过控制器。另一个改变是,当视图,或者表现层需要渲染动态页面时,它使用从控制器传递的数据而不是直接来自于模型层。这种改变去除了View 和Model 的耦合,允许控制器选择数据和显示这些数据的视图。

5  Struts 控制流

因为web 应用是动态的,所以很难表现“一个真正固定的控制流”。取决于环境,不同的方式下有很多不同的事情发生—特别是在web 应用中。但是事情仍然有一个通用的秩序。如果你是个Struts,应用框架,甚至web 应用的新手,这些流程刚开始可能难以跟得上(理解)。亟待解决的各种问题不一定那么明显。我们将在本书中慢慢详细涉及。首先,在介绍树木之前我们先认识这片森林。你读完此书后,我们建议你再次回来,看看每一部分是如何切合进这个总图的。

5.1 Struts 是富有效率的吗

详细描述完Struts 处理流程后,你可能会想知道这些的花多长时间。通常,Struts 应该能提升大部分正确设计的Web 应用的性能。在本节中,我们检查一些关系到框架效率的特殊设计点。

Struts不仅是线程安全(thread-safe)而且是线程依赖(thread-dependent)的Struts 使用轻量的Action 对象,而不是各个单独的servlet,来对请求处理响应。Struts 实例化每个Action 类一次,并允许其他请求通过原有的对象线程化。这种核心策略节省了资源,并提供最大的吞吐性。一个正确设计的应用将通过使用一个单独的Action 来路由各种相关操作来发挥这种特征。ActionForm bean最小化子类代码并缩短子类层次。Struts 框架的一个关键点是可以从请求中自动组装ActionForm bean 。没有这个组件, 用户不得不自行编写代码并实例化来组装每个bean 类。小心使用反射机制会节省不少资源,资源是有限的,并允许它们更好的使用。

Struts 标签库提供通用功能,Struts 一起提供的bean 和logic 标记库符合大部分JSP 标记的需要。它们减少甚至消除了编写额外标签的需要。JSP 规范就包含了JSP 中的标签重用。使用相同的通用标签3 次比使用3 次不同的标签来的有效率。

Struts 组件对应用来说都是可重用的框架绑定的工具可以在大部分应用中使用。BeanUtil.populate 方法就是个例子。这个方法用来从HTTP 请求组装一个ActionForm Bean,但也可以用来从其它类型的映射中组装一个FormBean。重用组件可以减少开销和节省资源。

Struts本地化策略减少了大量冗余JSP通过允许本地化页面在运行时才获取,国际化应用可以为每种可能需要的语言只提供一个单独的页面。同时,相同的消息系统也可以用于处理错误信息。同一对象提供了双重用途。

Struts设计为一个开放架构Struts 组件设计来是可以被应用子类化的,以便可以提供其它的服务功能。这使得开发人员可以扩展存在的类而不是重新编写新类。而且,Struts 也和应用共享资源。这时开发人员可以使用存在的组件,而不用编写和实例化它们自己的类。

Struts是轻量型架构类似的框架也许提供数百个类和几十个包。整个Struts 框架由5 个标记库和5 个核心包组成。

Struts是标准兼容的Strtus 在许多运行标准组件的容器上都工作的非常之好。

Struts是开源的,具良好的文档,这意味着开发人员可以检查源代码,找出一些潜在的瓶颈。而且Struts 是模型中立的。因为Struts 并没有对后端模型做任何假定,一个应用可以按其最有效率的方式实现模型层。Struts Actions 可以调用一系列助手类来访问需要的数据。一旦数据被检索到,对JavaBean的依赖,使Struts 更容易保持值对象,这样来减少了大量的模型层调用。

相关文章
|
10月前
|
前端开发 Java 网络安全
《SSH框架》Struts2
Struts(金属支架),在程序中表示起支撑作用的通用程序代码,Struts2是在Struts1框架的基础上融合了WebWork优秀框架升级得到的。
|
Java
Struts2【入门】(一)
这是Strtus的开山篇,主要是引入struts框架…为什么要引入struts,引入struts的好处是什么,以及对Struts2一个简单的入门….
111 0
|
XML Java 数据格式
Struts2【入门】(二)
这是Strtus的开山篇,主要是引入struts框架…为什么要引入struts,引入struts的好处是什么,以及对Struts2一个简单的入门….
165 0
Struts2【入门】(二)
|
前端开发 Java
|
XML 安全 Java
day25_day27_Struts2_学习回顾
day25_01_学习回顾    1、Struts2框架在三层架构中哪部分进行的再优化?    答:         表现层、MVC模式。2、Struts1和Struts2的一个显著区别是什么?    答:         Struts1的核心控制器是一个servlet。
1428 0
|
XML Java 数据格式
Struts2框架的搭建
搭建一个struts2的框架,在之前已经搭建过struts的框架了,这里的流程基本上差不多,详见 struts1的搭建 首先到官网上下载jar包,这里附一个git的链接struts2jar包下载 新建工程,将下载的jar解压至工程中,项目结构如下: 项目结构 接下来编写struts.
940 0
|
前端开发 Java 开发者
|
前端开发 Java 容器
|
Java 前端开发 Spring
|
Java
Struts2框架基础篇
首先,要了解Struts2框架中参数传递的大体流程: 服务器端的Web容器收到用户的请求(URL)——Struts2的核心控制器FilterDispatcher接受用户发起的请求,然后判断这个请求是交给action还是交给web组件来处理;如果请求的action或web组件不存在,就会报错404。在整个处理过程中,需要一个辅助对象: ActionMapper ,它会确定调用哪个Actio
1614 0