Struts framework technical user guide (1) (1)

Source: Internet
Author: User
  1. Introduction

1.1 Model-View-controller (MVC) Design Mode

Fixme-a general introduction to this mode is required. For more information, see design patterns of the Mechanical Industry Press.

1.2 map MVC concepts to struts Components

The struts architecture implements the concept of Model-View-controller design mode, which maps these concepts to the components and concepts of Web applications.

The main components of this system structure will be discussed in detail below.

1.3 model: system status and business logic JavaBeans

The model part of the MVC-based system can be divided into two sub-concepts: the internal state of the system and the behavior that can change the state. In terms of syntax, we can regard State information as a noun (thing) and behavior as a verb (changing the state of things ).

Generally, your application represents the State in the system as one or more JavaBeans and uses properties to indicate the State details. Depending on the complexity of your application, these beans can be self-contained (knowing how to permanently save their state information in some way), or can be positive (facades ), know how to obtain information from external data sources (such as databases) When a request is sent. Entity ejbs is usually used to indicate the internal status.

Large applications often express the system's possible business logic behavior as a method called by beans that can maintain state information. For example, you have a shopping cart bean saved in the session for each current user, which indicates that the current user decides the attributes of the purchased item. This bean has a checkout () method to verify the user's credit card, send the order to the warehouse to select the goods and shipment. Other systems respectively indicate the same behavior, or use session ejbs.

In some small applications, the same behavior may be embedded into the action class as part of the controller. This is appropriate when the logic is very simple or you do not want to reuse it in other environments. The Struts Framework supports all these methods, but it is recommended that the business logic ("what") and Action class ("what to do") be separated.

1.4 view: JSP page and Representation component

The view section of Struts-based applications is usually built using JSP technology. The JSP page contains static html (or XML) text called "template text", plus inserted Dynamic Content Based on the interpretation of special behavior tags. The JSP environment includes a set of standard behavior tags described by JSP specifications for their purposes, such . In addition, there is a standard mechanism to define your own tags. These custom tags are organized in the custom tag library.

Struts includes a broad user interface that is easy to create and a fully internationalized tag library. It works perfectly with actionform beans as part of the system model. The usage of these tags will be discussed in detail later.

In addition to JSP pages and Their contained behaviors and custom tags, commercial objects often need to be able to process themselves into HTML (or XML) based on their current status when being requested ). The output processed by these objects can be easily used. The standard behavior tag is included in the JSP page of the result.

1.5 Controller: actionservlet and actionmapping

The Controller part of the application is concentrated on receiving requests from the client (typically a user running a browser) and deciding what business logic functions to execute, then, assign the responsibility for generating the next user interface to an appropriate view component. In struts, the basic component of controller is an actionservlet servlet. This servlet is configured by defining a set of mappings (described by the Java interface actionmapping. Each ing defines a path that matches the requested URI and a complete Class Name of the action class (a class that implements the action interface). This class is responsible for executing the expected business logic, then, assign the control to the appropriate view component to create the response.

Struts also supports the ability to use the actionmapping class containing additional attributes other than the standard attributes necessary for running the framework. This allows you to save additional information specific to your application while still taking advantage of other features of the framework. In addition, Struts allows you to define the logic name to which the redirection will be directed. Such a behavior method can request the "Main Menu" Page (for example ), you do not need to know the actual name of the corresponding JSP page. This function greatly helps you to separate control logic (what to do next) and display logic (what is the corresponding page name ).

2. Create a model component

2.1 Overview

The application requirement documents you use are likely to focus on creating user interfaces. However, you should ensure that the processing required for each submitted request must be clearly defined. Generally, developers of model components focus on creating JavaBeans classes that support all functional requirements. The exact characteristics of beans required by a special application depend on the variation of specific requirements, but they can be divided into the following types. However, it is useful to first make a brief review of the "range" concept because it is related to beans.

2.2 JavaBeans and scope

In a web-based application, JavaBeans can be stored in (and accessed from) Different "attributes. Each set has different rules for set lifetime and saved beans visibility. In general, these rules defining the lifetime and visibility are called the ranges of these beans. The following terms are used in the JSP specification to define an optional range (define the equivalents in the servlet API in parentheses ):

Page-beans visible on a separate JSP page, with a limited lifetime to the current request. (Local variable in service () method) Request-beans visible on a separate JSP page, including all pages or Servlets contained on this page or redirected from this page. (Request attribute)

Session-All JSP and Servlet beans that are visible to a specific user session, spanning one or more requests. (Session attribute)

Application-beans visible to all JSP pages and servlets of a Web application. (Servlet context attribute)

It is important to remember that the JSP page of the same web application shares the same set of beans with servlets. For example, a bean is saved as a request property in a servlet, as shown in the following figure:


     
      MyCart mycart = new MyCart(...);request.setAttribute("cart", mycart);
     

Use a standard behavior tag to view the JSP page immediately redirected by the servlet, as shown in the following figure:


     
      <jsp:useBean id="cart" scope="request"class="com.mycompany.MyApp.MyCart"/>
     

2.3 actionform beans

The Struts framework generally assumes that you have created an actionform Bean (a class that implements the actionform Interface) for each input request in your application ). If you define such beans in your actionmapping configuration file (see "create Controller component "), the struts controller servlet automatically executes the following services for you before calling the appropriate action method:

Use appropriate keywords to check whether a user's session has an instance of bean of the appropriate class.

If there is no bean in the session range, a new bean is automatically created and added to the user's session.

Call the Set Method for each request parameter whose name corresponds to an attribute in the bean. This operation is similar to when you use the wildcard "*" to select all attributes and use the standard JSP behavior tag. .

When the updated actionform bean is called, it is passed to the perform () method of the Acton class to make these values take effect immediately.

When writing your actionform beans, remember the following principles:

The actionform interface does not require special implementation methods. It is used to identify the role of these specific beans in the entire architecture. In typical cases, an actionform bean only includes the get method and Set Method of the attribute, without commercial logic.

Generally, there is only a small number of input validation logic in an actionform bean. The main reason for such beans is to save most of the recent values entered by the user for the relevant form-or even when the error is detected-so that the same page can be rebuilt, there is a set of error information, so you only need to correct the error field. User input verification should be performed in the action class (if very simple) or in appropriate commercial logic beans.

Define an attribute for the fields in each form (using the getxxx () and setxxx () methods ). The field name and attribute name must match according to the Conventions of JavaBeans. For example, an input field named username will call the setusername () method.

Note that the meaning of a form discussed here does not necessarily correspond to a separate JSP page in the user interface. In many applications, it is common to extend a "form" (from the user's point of view) to multiple pages. Think about it, for example, the user interface that is usually used to navigate to the installer when installing a new application. Struts encourages you to define a separate actionform bean that contains all the field attributes. No matter on which page the field is actually displayed. Similarly, different pages of the same form should be submitted to the same action class. If you follow this suggestion, in most cases, the page designer can reorganize fields on different pages without changing the processing logic.

2.4 system status beans

The actual status of the system is usually expressed as one or more Java Bean classes whose attributes define the current status. For example, a shopping cart system contains a bean indicating the shopping cart, which is maintained by each individual shopper. This bean contains (among other things) a group of items that shoppers currently choose to buy. Separately, the system also includes storing user information (including their credit card and shipping address), directories of available projects, and beans of their current inventory levels.

For a small-scale system or state information that does not need to be stored for a long time, a group of system state beans can contain information of all the specific details that the system has experienced. Or, the system state beans indicates the information permanently stored in some external databases (for example, the customerbean object corresponds to a specific row in the customers table ), create or clear from the memory of the server as needed. Entity ejbs is also used in large-scale applications.

2.5 commercial logic beans

You should encapsulate the functional logic in your application into the method calls of the JavaBeans designed for this purpose. These methods can be part of the same class used for system state beans, or they can be an independent class dedicated to executing business logic. In the latter case, you usually need to pass system state beans to these methods for parameter processing.

To maximize code reusability, commercial logic beans should be designed and implemented so that they do not know that they are executed in the Web application environment. If you find that you must import a javax. servlet. * class in your bean, You can bind this commercial logic to the Web application environment. Consider reorganizing things to make your action class (part of the controller task, as described below) translate all the information that the request from the HTTP request is processed as a call to the Set Method of your commercial logic beans attribute, and then you can make a call to execute. Such a business logic class can be reused in an environment other than the Web applications they were originally constructed.

Depending on the complexity and scope of your application, the commercial logic beans can be a common JavaBeans that interact with the system status beans passed as parameters, you can also use JDBC to call common JavaBeans that access the database. For large applications, these beans are often stateful or stateless ejbs.

2.6 digress: access a relational database

Many Web applications use a relational database (accessed through a JDBC driver) to save permanent data related to applications. Other applications use entity ejbs for this purpose. They delegate ejbs themselves to determine how to maintain the permanent state. If you use ejbs for this purpose, follow the client design pattern described in the EJB specification.

A common design problem for Web applications based on direct database access is how to generate an appropriate JDBC connection object when accessing a low-level database. There are several ways to solve this problem-the following principle describes a recommended method:

Create or obtain a connectionpool class that allows a group of database connections to be shared by multiple users. Struts (currently) does not include such a class, but there are many such classes.

When an application is initialized, define a servlet with a "load at startup" value in the deployment descriptor. We will call this servlet the start servlet. In most cases, this servlet does not need to process any requests, so there is no Will point to it.

Configure and initialize a connectionpool instance in the init () method of the servlet, save it as a servlet context attribute (equivalent to a bean in the application range from the perspective of JSP ). It is usually convenient to configure the connection buffer pool based on the parameters passed to the startup servlet initialization.

The destroy () method that starts servlet contains the connection logic for releasing the connection opened by the connection buffer pool. This method will be called when the servlet container ends the application.

When the action class needs to call a method (such as "Insert a new customer") in the commercial logic bean that requires database connection, the following steps are performed:

Obtain a connection buffer pool object from the servelt context attribute for this web application.

Call the open () method of the connection buffer pool object to obtain a connection used in the action class call.

Call the appropriate method in the commercial logic bean and pass the database connection object as a parameter to it.

Call the close () method in the allocated join, which will cause the join to be returned to the buffer pool for reuse of other requests in the future.

A common programming error is that you forget to return the database connection to the buffer pool, which eventually leads to the use of all the connections. Be sure that the logic of the action class always returns the join, even when the commercial logic bean throws an violation.

Following the design patterns recommended above means that you can write your business logic classes without worrying about how they get a JDBC connection for use-simply include connection parameter. When your business logic class is used in a web application, assigning and releasing appropriate connections is the responsibility of the action class. When you use the same business logic class, for example, in a batch processing job, providing an appropriate connection is the responsibility of the application (this does not need to be obtained from the buffer pool, because most batch processing jobs run in a single-threaded environment ).

3. Create a view component

3.1 Overview

This chapter focuses on the task of creating the view component in the application, mainly using JSP technology. In particular, Struts not only provides interaction with input forms, but also supports the establishment of international applications. Several other view-related topics are also briefly discussed.

3.2 International messages

A few years ago, application developers were able to consider using only one language (or sometimes two) that only supported their own country) and usually only the residents of a number representation (such as date, number, and currency value. However, the explosive growth of web-based applications and the expansion of these applications on the Internet or other widely accessed Networks, in many cases, the border of a country has become invisible. This situation is transformed into a need for applications to support internationalization (often referred to as "i18n", because 18 is the number of letters between the letter "I" and the letter "N") and localization.

Struts is built on the Java platform to help establish international and localized applications. The key concepts to be familiar with are:

Locale-the Java class that supports internationalization is Java. util. locale. Each locale represents a special country and language selection (with an optional language variable), and a set of format assumptions, such as numbers and dates.

The resourcebundle-java. util. resourcebundle class provides basic tools to support messages in multiple languages. View more about the resourcebundle class and your JDK version in the document package.

Propertyresourcebundle-standard implementation of a resourcebundle class allows you to define resources using the same "name = value" syntax as initializing the properties file. This is very convenient to use to prepare resource packages for a message for a web application, because these messages are usually text-oriented.

The messageformat-java. Text. messageformat class allows you to replace a part of a message string with the parameter specified during runtime (in this case, it is a message obtained from a resource package ). This is useful when you create a sentence, but words appear in different languages in different order. The placeholder string {0} in the message is replaced by the first runtime parameter, {1} is replaced by the second runtime parameter, and so on.

Messageresources-Struts class Org. apache. struts. util. messageresources enables you to treat a set of resource packages as a database and allow you to request a specific message for a specific locale (usually corresponding to the current user, instead of the default locale request message in which the server runs.

For an international application, follow the steps described in the international documentation in the JDK documentation package to create an attribute file containing messages in each language. The following is an example.

Assume that your source code is built in the package com. mycompany. mypackage, so it is saved in a directory called COM/mycompany/mypackage (relative to your source directory. To create a resource package named com. mycompany. mypackage. myresources, you should create the following files in the COM/mycompany/mypackage directory:

Myresources. properties-contains messages in the default language of your server. If your default language is English, you may have an entry like this:


     
      prompt.hello=Hello
     

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.