STRUTS2 Basic Learning Summary

Source: Internet
Author: User
Tags knowledge base

13.1.1 Struts 2 's MVC pattern

The MVC pattern is divided into the following 3 layers:

View layer: The view is the V in MVC. This layer is mainly used to display the user interface, and the acquisition of user input information submitted to the Controller layer components.

Controller layer: The controller is the C in MVC. This layer is primarily used to receive request information submitted by the View-layer component and to invoke components in the model layer based on some business rules. You can also consider this layer as a bridge between the view layer and the model layer.

Model: The model is the M in MVC. The layer can continue to be subdivided into finer parts, such as the data access layer, the business logic layer, and so on. The components of this layer are primarily used to access the database and to process business logic.

  

Since Struts 2 is the MVC framework, you must include the sections corresponding to these 3 levels in struts 2. The sections in Struts 2 that correspond to the 3 levels of the MVC pattern are as follows:

View layer: Consists of JSP pages (including struts 2 tags) and some client-side code (HTML, JavaScript, etc.).

Controller layer: Consists of the action class of struts 2. The action class can be a Pojo class or a class that inherits from the Actionsupport class.

Model layer: The model layer in Struts 2 varies depending on the system business. Typically, the model layer consists of an entity class, a DAO class, and a service class.

The Struts 2 framework, as a concrete implementation of the MVC pattern, must be configured accordingly. In Struts 2 There is a core profile struts.xml, which is typically placed in the Web-inf\classes directory.

Struts 2 was developed on the basis of WEBWORK2.

Note: Struts 2 and struts 1 are almost different in code style.

Struts 2 has advantages over struts 1:

1. In software design, struts 2 is not tightly coupled with the Servlet API and struts API as struts 1 does.

Struts 2 applications can be independent of the Servlet API and the Struts API.

2. Struts 2 provides interceptors that can be programmed with an AOP using interceptors.

3, Struts 2 provides a type converter.

4, Struts 2 provides support for a variety of performance layer technology, such as: JSP, Freemarker and so on.

5, the input check of Struts 2 can be specified method for verification.

6, Struts 2 provides global scope, package scope and action scope of Internationalized resource file management implementation.

Struts 2 Architecture:

1. Web browser requests a resource.

2, Filter Dispatcher Find method, determine the appropriate action.

3, interceptors automatically apply common functions to the request, such as verification and file upload operations.

4. The Execute method of action is usually used to store and re-obtain information.

5. The result is returned to the browser.

Build Struts 2 development environment

1. Find the jar package needed to develop the application for Struts 2.

2, write the configuration file of Struts 2.

3. Join the Struts 2 MVC boot Framework configuration in Web. Xml.

Develop the least-used jar files for struts 2:

Core class Library of Struts-core-2.x.x.jar:struts 2 framework

Xwork-2.x.x.jar:xwork class Library, Struts 2 builds on it

Ognl-2.6.x.jar:object Graph Navigation Language, the Struts 2 framework through its properties of read-write objects.

Templates for UI labels for freemarker-2.3.x.jar:struts 2 are written using Freemarker.

COMMONS-LOGGING-1.1.X.JAR:ASF produced by the journal package.

Commons-fileupload-1.2.1.jar: File Upload component.

Struts 2 Various documents in detail:

1. struts.xml file

Struts.xml needs to be stored under web-inf/classes, the template is as follows:

 

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.1//en" "http://struts.apache.org/dtds/ Struts-2.1.dtd "><struts></struts>   

Struts.xml is the core configuration file for Struts 2, which is used primarily to configure action written by developers.

2. Web. xml file

In Struts 2, the Struts framework is started with filter and is configured in Web. Xml as follows:

  <!--configuring STRUTS2 core Filter--  <filter>      <filter-name>struts2</filter-name>      < filter-class>          org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter      </ filter-class>  </filter>  <filter-mapping>      <filter-name>struts2</ filter-name>      <url-pattern>/*</url-pattern>  </filter-mapping>

The default configuration file under the Classpath will be read in the Init () method of Strutsprepareandexecutefilter

Struts.xml completes the initialization operation.

 Note: After struts 2 reads the contents of the Struts.xml, it is stored in memory in javabean form, and struts 2 to the user

Each request processing will use the in-memory data.

Filter filters are a layer of handlers between a user request and a handler. It can handle the class capacity of user requests and handler responses, typically for permissions, encoding

Conversion and other occasions.

3, Actionsupport class

The Actionsupport class provides some default implementations for Action, mainly including predefined constants, fetching text resources from resource files, receiving validation error messages, and validating default implementations.

The application of Struts 2 data validation and validation framework:

1. Data check

The action inherits the Actionsupport class, which implements the action, Validateable, Validationaware, Textprovider, Localeprovider

Serializable interface.

The Validateable interface defines a validate () method that can be overridden in a user-defined Action class to implement validation functionality.

public class Loginaction extends actionsupport{     private String username;      Public String GetUserName () {        return username;    }         public void Setusername (String username) {        this.username = username;    }     @Override public    String execute () throws Exception {        //TODO auto-generated method Stub        if (! Username.equa LS ("HelloWorld"))        {            Map request = (map) actioncontext.getcontext (). Get ("request");             Request.put ("Name", GetUserName ());             return SUCCESS;        }        else return ERROR;     }     public void Validate ()    {          ///If the name is empty, the error message is Fileerror if        (this.getusername () = NULL for the action class of the Heroes | | This.getusername (). Trim (). Equals (""))        {            addfielderror ("username", "name cannot be empty");}}    }

After the calibration method is defined in the class, the method executes before executing the system's execute () method. If the method is executed, the fielderror of the action class already contains a data validation error message.

The request is forwarded to the input logical view, so it should be configured in the action configuration.

  

        <action name = "Loginaction" class = "Com.cnblogs.jbelial.login.LoginAction" >            <!--define mappings between 3 logical views and physical resources --            <result name = "Input" >/login.jsp</result>            <result name = "Error" >/error.jsp </result>            <result name = "Success" >/main.jsp</result>        </action>

Attention:

The name attribute in result has the following:

1, Success: Indicates that the request processing succeeds, this value is also the default value.

2. Error: Indicates that the request processing failed.

3, None: Indicates that the request processing is completed without jumping to any page.

4. Input: Indicates where the validation failure should be when the input is entered.

5. Login: Indicates the target of jumping after login failure.

2. Application of Struts 2 verification framework

Struts 2 provides a large number of data validators, including form field validators and non-form field validators.

(1) Required String Validator

The name of the validator is requiredstring and its validation rule definition file is as follows:

  

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.1//en" "http://struts.apache.org/dtds/ Struts-2.1.dtd "><validators>    <field name =" username ">        <!--field names of fields that need to be validated--        < Field-validators type = "Requiredstring" >            <!--go to space--            <param name = "Trim" >true</param>< c7/><!--Error message-            <message> Enter your user name </message>        </field-validators>    </ Field></validators>

File name: Actionname-validation.xml: Where ActionName is the name of the user-defined action class that needs to be validated. And the file should be placed with the action class file in the

The same path.

(2) must fill checker

The name of this validator is required. The difference between this validator and requiredstring is that you can have an empty string. The configuration is as follows:

  

        <!--fields that need to be validated field names--  
    <field name = "username" >        <field-validators type = "Required" >             <!--error message--            < message> Please enter your username </message>        </field-validators>    </field></validators>

(3) Integer checker

The validator is named int, and the validator requires that the integer value of the field must be within a certain range. The configuration is as follows:

  

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.1//en" "http://struts.apache.org/dtds/ Struts-2.1.dtd "><validators>    <!--field name to validate field--    <field name =" number ">        < Field-validators type = "int" >             <!--The minimum value of the value-            <param name = "min" >50</param>            <!-- Maximum Value--            <param name = "Max" >100</param>            <!--error message--            <message> Size must be between 50 and 100 </message>        </field-validators>    </field></validators>

  

(4) Date Calibrator

The validator's name is date, and the validator requires that the date value of the field must be in the specified range class, so there are also min and Max parameters. Configuration format:

  

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.1//en" "http://struts.apache.org/dtds/ Struts-2.1.dtd "><validators>    <!--field names for fields that need to be validated--    <field name =" date ">        < Field-validators type = minimum value of "date" >             <!--time-            <param name = "Min" >1900-01-01</param>            < maximum!--time--            <param name = "Max" >9999-01-01</param>            <!--error message--            < Message> time must be between 1900-01-01 and 9999-01-01 </message>        </field-validators>    </field>< /validators>

(5) Email Address checker

The name of the validator is email, which requires the character of the field to be a legitimate e-mail address if it is not empty. The format is as follows:

  

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.1//en" "http://struts.apache.org/dtds/ Struts-2.1.dtd "><validators>    <!--field names for fields that need to be validated--    <field name =" Email ">        < Field-validators type = "Email" >              <!--error message-            <message> Invalid email address </message>        </ Field-validators>    </field></validators>

(6) URL Checker

The name of the validator is the URL, which requires that the character of the field be a valid URL address if it is not empty. The format and (5) mailbox checker are similar.

(7) Character wear length calibrator

The name of the validator is stringlength, which requires that the character length of the field must be between the specified range, so it has minLength and maxLength two parameters.

It has the same number as the (3) integer checker.

(8) Regular Expression checker

The name of the validator is the regex, which checks whether the checked field matches a regular expression.

3. Struts 2 Interceptor:

Most of the Struts 2 framework is done with interceptors, and when Filterdispatcher intercepts a user request, a large number of interceptors will process the user request and then call the user

Customize the method in the action class to handle the request.

Interceptor Configuration:

Defined in the Struts.xml file, using the <interceptor.../> element, in the following format:

<interceptor name = "Interceptor Name" class = "Interceptor implemented Classes" >

<param name = "parameter name" > Parameter value </param>

</interceptor>

Where <param.../> can be omitted, but at some point it is necessary to pass in the interceptor parameters.

Sometimes an action configures more than one interceptor, often using multiple interceptors for filtering. This is the time to configure the interceptor stack consisting of several interceptors. Defining Interceptor Stacks

<interceptor-stack.../>, format as follows:

<interceptor-stack name = "Interceptor Stack name" >

<interceptor-ref name = "Interceptor One" ></interceptor-ref>

<interceptor-ref name = "Interceptor Two" ></interceptor-ref>

<interceptor-ref name = "Interceptor Three" ></interceptor-ref>

</interceptor-stack>

  Note: When configuring the Interceptor stack, the interceptor used must be an existing interceptor. The Interceptor stack can also refer to the interceptor stack.

  

Interceptor Implementation class:

Struts 2 provides a number of interfaces or classes for programmers to customize interceptors. such as: Com.opensymphony.xwork2.interceptor.Interceptor interface.

There are three methods in this interface:

void init (): Used to initialize resources.

String Intercept (actioninvocation invocation): The action used to implement the interception.

Destroy (): Used to destroy the resource opened in the Init () method.

Category: Java EE good text to the top concern me to collect the article Hezoan
Follow-7
Fans-142 + plus attention3«Previous: Jsp/servlet implementation of a simple message board
» Next: Hibernate Basic Learning Posted @2012-05-10 16:59 Hezoan Read (27128) Comment (3) Edit Collection List of comments #1楼2016-03-16 10:43 LiuhongjunIt's very clear, thanks for the support (0) against (0) #2楼2016-03-31 11:28 souiedLogic clear Support (0) objection (0) #3楼2016-04-16 18:43 WmzsoftOpen source plug-in development platform based on Struts2 JXADF quite NB, online demo address: http://osgia.com Support (0) objection (0)Refresh Comments Refresh page back to topRegistered users can post a comment, please login or register, visit the homepage of the website. "Recommended" 500,000 lines VC + + Source: Large configuration industrial control, power simulation CAD and GIS Source Library
"Recommended" Melt Cloud Instant messenger cloud-beans Fruit Gourmet, Faceu and other billion-level apps are in use
"Recommended" Report development has a shortcut: Quick design, easy integration, data visualization and interaction
"Recommended" one months only 630 yuan to earn 15000 yuan, learn to invest
"Recommended" Ali public opinion first Open, 69 Yuan limited seconds to kill Latest IT News:
· Google intends to test wireless fiber broadband services in 24 locations in the United States
· 10 Big Data technologies that programmers need to focus on
· Monthly income millions of to fiasco: What did the college student go through?
· Google and Savannah Design Academy collaborate on new projects to nurture future UX designers
· Those who buy Ali at $120 may have a chance to unpack.
» More News ... Latest Knowledge Base articles:
· Program Monkey Daughter-in-law attention matters
· But girl, why do you have to program it?
· Know what it is (take algorithmic learning as an example)
· How to give a short and unambiguous name to a variable
· The wisdom of programming» More Knowledge Base articles ...

Struts2 Basic Learning Summary

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.