Struts Principles and Practices

Source: Internet
Author: User
Tags tld

Part 1)

1. What is struts?

Frameworks are reusable and semi-finished applications that can be used to generate specialized custom programs.

As long as you carefully study the real application, you will find that the program is generally composed of two different types of components, one of which is closely related to the specific transactions to be processed by the program, we may call them business components, and application services. For example, a tax collection and administration system and a book management system may differ greatly in processing their businesses, these components that directly process the business are unlikely to be reused in different systems due to different business nature, other components, such as control of program flow, input validation, error handling, and tag library, can be reused in different systems only for Program-related components. People naturally want to extract something that has common characteristics in different applications into a semi-finished program. Such a semi-finished product is a so-called program framework, you don't have to start from scratch to create a new one. Instead, you can build it on this basis. In fact, some large software companies choose to build such a framework on their own. However, most small and medium software enterprises or other organizations do not have the conditions to build their own frameworks.

As an open source code application framework, Struts has developed rapidly in recent years and has been widely used in JSP web application development, in some documents, it has become the de facto standard of the JSP web application framework. So what is struts?

To answer this question, we have to start with two basic structure modes of JSP web applications: Model 1 and Model 2. In order to give readers some practical help, and tries to make the learning curve more flat. I want to use the instance-driven method to answer questions in depth step by step, because, the best way to learn a technology is to learn it in practice, understand it in practice, and gradually deepen understanding and grasp the essence of its spirit, rather than introducing a lot of new concepts at the beginning to make everyone feel at a loss, or stick to a bunch of concepts and be helpless in the face of a real demand. Just as, even if a person becomes a swimming doctor in a book, as long as he is not in the water, I think he is unlikely to actually swim.

The structure 1 of model 1 is shown below:

Figure 1

Mode1 is a mode centered on JSP files. In this mode, JSP pages are not only responsible for expressing logic, but also for controlling logic. This processing method is called logical coupling on pages in professional books. It does not have much harm for small-sized projects such as a simple guestbook. In fact, when people start to access something new for themselves, for example, when using JSP to access the database, they tend to like the ability of others to provide a single JSP page containing all this, in this way, you can grasp the global information on a page for easy understanding. However, when Model 1 is used for large-scale development, the program flow is determined by pages that are mutually perceptible. When there are many pages, it is very complicated to clearly grasp the flow, when you modify a page, many related pages may be affected, which makes it very difficult to modify and maintain the program; another problem is that program logic development and page design are entangled, which neither facilitates division of labor and cooperation nor facilitates code reuse. Such a program has poor robustness and scalability.

When Grady booch and others emphasize the importance of modeling in the UML user guide, A metaphor for making a dog's nest, a private house, and a building shows that people should adopt the same reasonable method when dealing with things of different sizes, people should adopt different models for applications of different sizes.

To overcome the defects of model 1, Model 2 is introduced as follows:

Figure 2

It introduces the concept of "controller". Generally, the controller is served by Servlet. client requests are not directly sent to a JSP page that processes business logic, but to the Controller, then, the Controller calls different transaction logic based on the specific request and returns the processing result to the appropriate page. Therefore, this servlet Controller provides an application with a hub for front-and back-end processing. On the one hand, it provides an appropriate entry point for the verification, identity authentication, logs, and international programming of input data; on the other hand, it also provides the possibility of separating the business logic from the JSP file. After the business logic is separated from the JSP page, the JSP file is transformed into a view that simply completes the display task. The independent transaction logic becomes the model that people often say, and the controller control itself constitutes the MVC mode. Practice has proved that the MVC mode provides great convenience for the development and maintenance of large programs.

In fact, MVC is not a pattern proposed for Web applications at the beginning. Traditional MVC requires m to report its status changes to v, however, it is difficult to achieve this because Web browsers work in a typical pull mode rather than push mode. Therefore, some people call MVC for Web applications MVC2. As mentioned above, MVC is a pattern. Of course, there can be various specific implementations, including you can implement a program framework that reflects the MVC idea by yourself, struts is a program framework that implements MVC2. Its general structure is as follows:

Figure 3

Figure 3 outlines the structure of a Struts-based application, from left to right, including its presentation layer (view), control layer (Controller), and model layer (model ). The presentation layer is built using the struts tag library. All requests from the client that need to pass the framework are received by the servlet called actionservlet (actionservlet struts has already been written for us, as long as your application has no special requirements, it basically meets your requirements), according to the received request parameters and Struts configuration (struts-config.XML) in actionmapping, send the request to the appropriate action to handle, to solve the problem of who do, they constitute the struts controller. Action is a component that really works in struts applications. Developers usually spend a lot of time here. It solves the problem of what they do, it calls the required business components (models) to complete the application business. The business components solve the problem of how to do it, return the execution result to an actionforward object representing the JSP (or action) that depicts the response to the actionservlet to present the response to the customer.

Process 4:

Figure 4

Here, we need to note that action is the class. As mentioned above, it is the place where struts really works and deserves our high attention. However, there are two different opinions on whether it belongs to the control layer or model layer. One thinks it belongs to the model layer, for example, JSP web programming guide; others consider it as a part of the controller, for example, programming Jakarta Struts, mastering Jakarta Struts, and Struts kick start, other books such as struts in action also recommend that you avoid placing the business logic in the action class. That is to say, the content in the brackets after action in Figure 3 should be removed from it, however, some systems actually put the simple business logic that is not intended to be reused in the action, so it is shown in the figure. Obviously, separating a business object from an action is conducive to its reuse. It also enhances Application robustness and design flexibility. Therefore, it can actually be seen as an adapter between the Controller and the model. If you want to attribute it to that part, I prefer the latter view, that is, it is part of the controller. In other words, it should not contain too much business logic, but should simply collect the data required by the Business Method and pass it to the business object. In fact, its main responsibilities are:

 

  • Verification prerequisites or statements
  • Call the required business logic method
  • Detect or handle other errors
  • Route Control to related view

    The simple description above may make it unacceptable for beginners. Here is a more specific example to help us better understand it. For example, assume that we are working on an e-commerce program. The task to be completed is to submit an order and return the order number to the customer, it should be completed by the action class, but how to obtain the database connection, insert the order data to the database table, and how to obtain the order number from the database table (usually the data in the auto-increment data column ), this series of complex problems are all about how to solve them. It should be done by a (assuming the name is orderbo) business object, that is, model. Orderbo may use a method named submitorder that returns an integer value to do this. The action is to first check whether the order data is correct, so as to avoid the garbage; if it is correct, simply call the submitorder method of orderbo to obtain the order number. It also needs to handle any errors that may occur during the call process. Finally, different results are returned to the customer according to different situations.

    Ii. Why should I use the Struts framework?

    Since this article has started, I can build this framework myself. Why should I use struts? The reasons I want to list below are obvious: first, it is built on a well-recognized pattern like MVC, and Struts is involved in both M, V, and C, but it mainly provides a good controller and a set of custom tag libraries, that is, it focuses on C and V. Therefore, it naturally has a series of advantages brought by MVC, for example, the structure is well-defined and highly reusable. It increases the robustness and scalability of the program, facilitates the division of development and design, and provides centralized and unified permission control, verification, internationalization, and logs. Second, it is an open-source project, including its inventor Craig R. some program masters and masters, including McClanahan, are continuously and carefully cared for, and have undergone practical tests, making them more and more powerful, and the system is improving. Finally, it shows good integration with other technologies and frameworks. For example, now it has been integrated with tiles and can be predicted, it will soon be integrated with JSF and so on. Of course, like any other technology, it is not perfect, for example, it is somewhat casual in naming classes and some attributes and parameters, causing some inconvenience; for example, the action class execute method can only receive one actionform parameter. However, it is widely used without affecting it.

    Iii. Struts installation and basic configuration

    We will mainly explain struts1.1. Here we assume that the reader has configured the Java Runtime Environment and the corresponding Web Container. In this example, j2sdk and atat4.1.27 are used. Next, we will introduce the basic part of step by step.

    Install struts
    To the http://jakarta.apache.org/download struts installation file, this example uses version 1.1.

    Next, perform the following steps to complete the installation:
    1. Unzip the downloaded installation file to your local disk.
    2. generate a new Web application. Assume that the root directory of the generated application is /Webapps/mystruts directory. Create an alias for the application in the server. xml file, such as/mystruts.
    3. Copy the following JAR files from the files decompressed in step 1 /Webapps/mystruts/WEB-INF/lib directory, the main files are as follows.

      struts.jarcommons-beanutils.jarcommons-collections.jarcommons-dbcp.jarcommons-digester.jarcommons-logging.jarcommons-pool.jarcommons-services.jarcommons-validator.jar

    4. Create a web. XML file, which is a deployment description file required by servlet-based Web applications. A struts web application is essentially a servlet-based Web application.

    Struts has two components to be configured in this file: actionservlet and tag library. The following is a configuration list:

      <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app>  <servlet>    <servlet-name>action</servlet-name>    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>    <init-param>      <param-name>config</param-name>      <param-value>/WEB-INF/struts-config.xml</param-value>    </init-param>    <init-param>      <param-name>debug</param-name>      <param-value>2</param-value>    </init-param>    <load-on-startup>2</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>action</servlet-name>    <url-pattern>*.do</url-pattern>  </servlet-mapping>  <taglib>    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>  </taglib>  <taglib>    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>  </taglib>  <taglib>    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>  </taglib></web-app>

    Above we complete the basic configuration of Servlet and tag library in Web. XML, and more framework components need to be configured in struts-config.xml:

    5. Create a basic struts-config.xml file and place it in /Webapps/mystruts/WEB-INF/directory, the file is based on the struts application configuration description file, it combines the components in the MVC structure, it is constantly enriched and changed during development. In struts1.0, an application can only have one such file, which makes Division of Labor Development inconvenient. In struts1.1, there can be multiple such files to overcome these shortcomings. The components to be configured in this file include: data-Sources

  • Global-execptions

    Form-beans

    Global-forwards

    Action-mappings

    Controller

    Message-Resources

    Plug-in

    The configuration list is as follows:

      <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config>  <message-resources parameter="ApplicationResources" /></struts-config>

    So far, we have the various components required to complete the simplest struts application. As mentioned above, during the development process, we will constantly enrich and modify the above two configuration description files. Next we will make a very simple application to experience the real process of struts application development, in order to have a real understanding of it. After completing the introduction of the basic section, I will provide some examples that are frequently used in actual development and make beginners feel a little difficult. Finally, we will introduce the relationship between struts and other frameworks and examples of generating applications by combining them.

     

    Next, we will start with a simple logon example to have a clear and intuitive understanding of the main parts of struts. This example is very simple. Assume that there is a user named LHB whose password is aWave. The task to be completed by the program is to present a logon interface to the user, if both the name and password entered by the user are correct, a welcome page is returned to the user. Otherwise, the logon page is returned, asking the user to log on again and display the corresponding error information. This example is used repeatedly in the basic section of struts. This simple program is used as an example because we do not want to dilute our theme with overly complicated business logic.

    Because struts is a framework built on the MVC design pattern, you can follow the standard development steps to develop your struts web application. These steps can be roughly described as follows:
    1 Define and generate all views representing the user interfaces of the application, and generate all actionforms used by these views and add them to the struts-config.xml file.
    2. Add the necessary messageresources project to the applicationresource. properties file.
    3. Generate the application controller.
    4 define the relationship between views and controller in the struts-config.xml file.
    5. model components required for generating applications
    6. Compile and run your application.

    (Part 1)

     

     

    (Part 3)

    I. Working Principle of JDBC

    Struts is essentially a Java program. to access a database in a struts application, you must first understand the working principle of Java Database Connectivity API (JDBC. As its name reveals, the JDBC Library provides an underlying API to support basic SQL functions independent of any specific SQL implementation. Provides basic database access functions. It is a class and interface that extracts the public concepts of various database access. The jdbc api includes two packages: Java. SQL (called the JDBC kernel API) and javax. SQL (called the JDBC standard extension ). They are combined and contain the classes required to develop database applications using Java. These classes or interfaces mainly include:
    Java. SQL. drivermanager
    Java. SQL. Driver
    Java. SQL. Connection
    Java. SQL. Statement
    Java. SQL. preparedstatement
    Java. SQL. resultset

    This makes it easier to send SQL statements from Java programs to databases, and is suitable for all SQL dialects. That is to say, after a Java application has been written for a database such as Oracle, there is no need to write it again for ms SQL Server. Instead, the same Java application can be used for various database systems. This statement may be unacceptable to everyone. Here we can make an example: participants from the Member States of the United Nations during the United Nations Meeting (equivalent to the specific database management system here) often all have their own language (dialect ). Speakers of the conference (equivalent to the Java application here) cannot speak in various languages. You only need to use one language (equivalent to JDBC here) to speak. So how can we ensure that all the participants in the Member States understand the speech? It depends on simultaneous translation (equivalent to the JDBC driver here ). In fact, the driver translates the SQL statements in the Java program into statements that can be executed by a specific database, and then submits them to the corresponding database management system for execution. Therefore, when using JDBC APIs to access a database, we need to adopt different drivers for different databases. The driver is actually suitable for specific implementation of the database JDBC interface, they generally have the following three functions:

     

    In theory, UTF-8 encoding characters can be up to 6 bytes long, but 16-bit BMP characters can be up to 3 bytes long.

    Bytes 0xfe and 0xff are never used in UTF-8 encoding.

    Through the form of UTF-8, Unicode can finally be used in a wide range of situations. Before discussing struts's international programming, let's take a look at how we used to handle Chinese problems in JSP programming and what we often encounter:

    Ii. causes and solutions for garbled Chinese Characters

    The Java kernel is Unicode, that is, Unicode is used to represent characters when the program processes characters, but the file and stream are stored in byte streams. In the Basic Data Type of Java, char is Unicode and byte is byte. Therefore, Java needs to convert byte streams and char in different links. If the character set encoding is improperly selected during this conversion, garbled characters may occur.

    There are several common garbled characters:
    1. The Chinese character is changed to a question mark "? "
    2. Some Chinese characters are correctly displayed, while others are incorrectly displayed.
    3. garbled characters are displayed (some are Chinese characters but not as expected)
    4. garbled characters in read/write Databases

    Next we will explain the causes of these problems one by one:

    First, we will discuss the question of converting Chinese characters into question marks.

    In Java, byte and Char are converted to each other in the sun. Io package. The common conversion methods from byte to Char are as follows:
    Public static bytetocharconverter getconverter (string encoding );

  • 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.