STRUTS2 Study Notes (Overview)

Source: Internet
Author: User

STRUTS2 Study Notes

March 7, 2015 11:02:55

MVC thought

The MVC correspondence between Strust2 is as follows:

Of the MVC three modules, the STRUTS2 correspondence is as follows:

Model:

Responsible for encapsulating the status of the application and implementing the application functionality. Usually divided into data model and business logic model, the data model is used to store business data, such as order information, user information, and business logic model contains the business operations of the application, such as the addition or modification of orders.

Encapsulation Application state: Some application data is encapsulated so that the view can only get the corresponding data through the interface

Response status query: Processing of application state changes

Exposure application function: Exposed interface

Notification view changes: Proactively passing data to a view

Controller:

Used to control the process of the application and to process requests made by the view. When the controller receives the user's request, the user's data is matched with the update of the model, that is, the function of invoking the model to implement the user's request, then the controller chooses the view for the response and presents the updated data to the user.

Accept and validate the data for the HTTP request: for a URL request, distribute the request through the controller to the specified processing module.

Mapping updates to the user data domain model: Changes to the user data model do not immediately correspond to model, but require a controller to distribute

Select the view to use for the response: Select a view corresponding to a model according to the profile

View:

Used to present the contents of the model to the user, who can request the model to be updated through the view. The view obtains the data to be displayed from the model, and then presents it to the user in its own way, which is equivalent to providing the interface to interact with the user, and when the user is working on the interface or completing the completion, it makes a request to the controller by clicking the Submit button or other triggering event.

Data for the Analytic model: functions such as velocity

Generate HTML response:

Update of request model: send form to Background

Send user input to Controller

Struts2 Work Flow

The processing of a request in the STRUTS2 framework is roughly divided into the following steps:

    1. Client initiated a (HttpServletRequest) request
    2. The request is submitted to a series (mainly three layers) of filters (filter), such as Actioncontextcleanup, other filters, Sitemesh, etc., Filterdispatcher. Note that there are sequential, first actioncontextcleanup, and then other filters (Sitemesh, etc.), and finally to Filterdispatcher.
    3. Filterdispatcher is the core of the controller, which is the core of control layer in MVC. Filterdispatcher to initialize and enable core Dofilter
    4. Actionproxy through Configuration Manager (Struts.xml) to ask for the framework profile and find the action class that needs to be called.
    5. Actionproxy creates an instance of Actioninvocation while Actioninvocation invokes the action through proxy mode. But before the call, Actioninvocation will load all interceptor related to the action based on the configuration. (Interceptor is the concept of another core level of struts2)
    6. The Interceptor scheduling process is as follows:
      1. When actioninvocation is initialized, all interceptor associated with the action are loaded according to the configuration.
      2. When the action implementation is invoked by the Actioninvocation.invoke method, the interceptor is executed.

Overall process

L Client submits a HttpServletRequest request (action or JSP page).

L request is submitted to a series of filter filters, such as Actioncleanup and Filterdispatcher.

L Filterdispatcher is the core of the STRUTS2 controller, which is usually the last filter in the filter chain.

When the request is sent to Filterdispatcher, Filterdispatcher asks the Actionmapper to call an action to process it.

L if Actionmapper decides to call one of the Action,filterdispatcher, give the request to actionproxy for processing.

L Actionproxy through Configuration Manager to ask the framework's profile Struts.xml to find the action class that was called.

L Actionproxy Creates an actioninvocation instance that invokes action through the proxy mode.

When the action is completed, a result string is returned, which is then passed through the Intercepter interceptor in reverse order.

The final actioninvocation instance, which is responsible for configuring the result element according to the Struts.xml, finds the corresponding result and determines the further output.

Action

Struts2 the action Life cycle

Struts2 the action Interface Isolation

The action in STRUTS2 does not need to depend on a particular web container. We don't see objects related to Web containers like httpservletrequest,httpservletresponse.

question: Struts2 of the Action does not carry any Web container-related objects, Action and how it works in Web in the container?

Although Struts2 's action is a very common Java object and does not have any characteristics of the Web container, we need to put the action in a much larger context. In fact, STRUTS2 provides a complete data environment and execution environment for action execution. This execution environment ensures that the action runs smoothly in the Web container.

In Struts2, each HTTP request is sent to a filter. This filter, for each request, will create a code execution environment, and on this basis, for each execution environment with the corresponding data environment, the content of this data environment from the Web container of one another object. This makes it possible to invoke the action execution code without worrying about whether it is running in the Web container.

question: Struts2 of the Action does not carry any Web container-related objects, Action and how to Web container to communicate and obtain Web What about the container's related objects?

We just mentioned that STRUTS2 will establish an execution environment and data Environment for each HTTP request. Where the data environment becomes the basis for the action to get the Web container. Therefore, when the action needs to get the related object of the Web container, it needs to be done through the data environment.

Struts2 Advantages of setting

1. Makes Struts2 's action very easy to test

If we do not consider the execution environment of the action at all, just think of action as an ordinary Java object, then we can even directly new an action object, by executing the method to complete the test. In this way, we don't need any mock to simulate the environment of the Web container.

2. Combine the execution environment of action, so that Struts2 can define a richer level of execution at the control level

Because the action is an ordinary Java class, not a servlet class, completely detached from the Web container, we can make it easier to design the control layer in a reasonable hierarchical manner, thus abstracting out many common logic and leaving the logic out of the action object itself. In fact, Struts2 is doing the same, whether it is interceptor, or result, in fact, is abstracted out of the action of the public logic, put them outside the action, thus simplifying the development of the action.

3. Makes the Struts2 action look more like a pojo, making it easier to manage

The Struts2 action is a thread-safe object. The parameters passed by the Web container are also passed to the member variable in the action. In this way, the action looks more like a pojo, which can be easily managed by many object containers. For example, you can easily include action in the spring container for management.

Data Interaction Context Actioncontext (Beatcontext)

Because the action is expected for one URL after another, the Actioncontext should have the following features:

1. Actioncontext should be the bridge between action and Web container

2. You should save more information about a request in Actioncontext

3. Actioncontext should be a thread-safe class object

Struts2 Interceptors and filters

The difference between interceptors and filters:

1, interceptors are based on the reflection mechanism of Java, and filter is based on function callback

2. The filter relies on the servlet container, while the interceptor does not depend on the servlet container

3. interceptors only work on action requests, while filters can work on almost all requests

4. The Interceptor can access the action context, the object in the value stack, and the filter cannot

5, in the life cycle of the action, the interceptor can be called multiple times, and the filter can only be called once when the container is initialized

Filter filters

First, the STRUTS2 filter is discussed, the main filter of STRUTS2 is Filterdispatcher, which is equivalent to the controller in the MVC framework, and has the following functions:

(1) Perform the actions: The filter uses the Actionmapper object to determine if the action should be mapped to it. If the Mapper object indicates that he should be mapped, the filter chain will be terminated and the action is invoked. This is very important, if you use Sitemesh filter at the same time, the Sitemesh filter should be placed before the filter, otherwise the action output will not be decorated.

(2) Clear Actioncontext: Filter to ensure memory overflow, will automatically clear the Actioncontext. This can be problematic when integrating with other frameworks, such as Sitemesh (a consistent Web page layout framework, like adorners). Actioncontextcleanup provides some information on how to handle these issues. The Actioncontextcleanup interceptor has been configured with Filterdispatcher configured.

(3) Maintain static content: Filters also maintain some of the common static content used in Struts2, such as JavaScript files, CSS files, and so on. Search for requests within the/struts/* range, and then map the values that follow/struts/to some of the public packages of struts, or you can search in your classpath.

By default, the following packages are found: Org.apache.struts2.static.template. This way you only use the request/struts/xhtml/styles.css,xhtml UI theme The default style sheet will be returned. Similarly, the JavaScript files required by the AJAX UI component can also be found in the Org.apache.struts2.static package. If you want to add other packages that are being searched, set the filter in Web. XML by setting a comma-separated list of package values for the "actionpackages" initial parameter.

(4) Clear the interceptors of xwork in the request life cycle

Custom Filters

It should be known that if we define the filter itself, it is to be placed in the STRTUS2 filter before, if placed in the STRUTS2 filter, your own filter action on the action of waste, will not be effective! Unless you are visiting jsp/html!

So I have a need now, I have to use the action environment, and I want to do something with the filter before executing the action, I can't do it with Filterdispatcher.

Then Strutsprepareandexecutefilter can split him into Strutspreparefilter and strutsexecutefilter, and we can add our own filters between the two filters.

Filters can also be defined by themselves, and in the case of using the new Strutsprepareandexecutefilter as the core filter, the custom filters can be placed in various positions.

The specific configuration is configured in Web. Xml.

Interception device

When using interceptors, you must finally refer to the STRUTS2 default stack defaultstack in action, as follows:

<interceptor-ref name= "checkbox" >
<param name= "Uncheckedvalue" >0</param>
</interceptor-ref>
<interceptor-refname= "Defaultstack"/> ( must add, otherwise error )

The Strust2 interceptor constitutes the interceptor stack, which, in the course of use, is equivalent to recursive invocation of the Intercept method of these interceptors. Usually we use Struts2 's default interceptor to develop ourselves, then follow these steps:

1 Customize a class that implements the Interceptor interface (or inherits from Abstractinterceptor).

2 Register the Interceptor defined in the previous step in Strutx.xml.

3 The interceptor defined above is referenced in the action that needs to be used, and the interceptor can be defined as the default interceptor for convenience, so that all actions are intercepted by the interceptor without special declarations.

Development

The Interceptor interface declares three methods:

Public interface Interceptor Extendsserializable {

void Destroy ();

void Init ();

String Intercept (actioninvocation invocation) throws Exception;

}

The Init method, after the Interceptor class is created, is called before the action image is intercepted, which is equivalent to a Post-constructor method, which allows the Interceptor class to do the necessary initial session operations.

The Destroy method is called before the Interceptor is garbage collected, and is used to reclaim resources initialized by the Init method.

Intercept is the main interception method of interceptors, if you need to invoke the subsequent action or interceptor, just call the Invocation.invoke () method in the method, before and after the method call can insert the action call before and after the interceptor needs to do the method. If you do not need to invoke subsequent methods, you can return an object of type string, such as action.success. In addition, Abstractinterceptor provides a simple implementation of the Interceptor.

Registering interceptors

<interceptors>

<interceptor name= "Login" class= "Com.jpleasure.teamware.util.CheckLoginInterceptor"/>

<interceptor-stackname= "Teamwarestack" >

<interceptor-refname= "Login"/>

<interceptor-refname= "Defaultstack"/>

</interceptor-stack>

</interceptors>

Set the above interceptor as the default interceptor

<default-interceptor-refname= "Teamwarestack"/>

This will be intercepted by login before all actions within the same package are executed.

Each interceptor has two default parameters:

Excludemethods-Filter out methods that do not use interceptors and

includemethods– method of using interceptors.

A few points to note:

1 the order in which interceptors are executed is executed in the order defined

2 Use the default interceptor to configure the interceptor stack required for each action

3 How to access Httpservletrequest,httpservletresponse or httpsession

There are two ways to achieve the effect, using Actioncontext:

Map attibutes =actioncontext.getcontext (). GetSession ();

or implement the appropriate interface:

HttpSession Sessionaware

HttpServletRequest Servletrequestaware

HttpServletResponse Servletresponseaware

Remaining parts

Integrated Spring and Hibernate

OGNL and tags

Advanced Topics

STRUTS2 Study Notes (Overview)

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.