Hand-hit struts knowledge points

Source: Internet
Author: User

Introduction to Struts2

1. Mvc principle

MVC (Model-view-controller), program design concept

Views do not say much, HTML, JSP, etc.

Controller, Broker, assign what each component should do, accept parameters and jump to other processing servlet, action

Model

Actionfrom in struts is a set of business JavaBean implementations. Encapsulates the form data, interacts with the page form, and passes the data; JavaBean is used to process real business requests

2. Produce

Struts+webwork

3. Structural system

Client sends strutsprepareandexecutefilter-->struts.xml-->action-->result.jsp (or other action, etc.) in the request-->web.xml

STRUTS2 Environment Configuration

1. Import jar file in Lib

I'm using a struts2.3.24,9 jar.

Struts2-core-2.1.24.jar

Xwork-core.2.1.6.jar

Ognl-2.7.3.jar

Commons-logging-1.0.4.jar

Freemarker-2.3.15.jar

Commons-io-1.3.2.jar

Commons-fileupload-1.2.1.jar

Javassist-3.11.0.ga.jar

Commons-lang3-3.2.jar

2. config filter in Web. xml

The filter named Struts2,class path is

Org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

3. New Struts.xml under SRC

Format:

<?xml version= "1.0" encoding= "UTF-8"?>

<! DOCTYPE struts public software foundation//dtd struts Configuration 2.3//en "

"Http://struts.apache.org/dtds/struts-2.3.dtd" >

<struts>

<constant ......../>

...

<package>

...

</package>

</struts>

Action Object

1. Actionj interface

public interface action{

public static final String success= "SUCCESS";

public static final String none= "NONE";

public static final String input= "INPUT";

public static final String login= "LOGIN";

public static final error= "ERROR";

Public String Execute () throws Exception;

}

Mainly describes the input constant, when struts passes validate validation failure, the system automatically returns input, so the result page will look for the property named input

2. Create an Action object

You can create a class directly, and then implement the action interface to implement the Execute () method

Create a class that inherits from the Actionsupport class and only needs to implement execute () in that class. Recommended, because Actionsupport is a tested canonical class that implements or inherits multiple interfaces such as validate, which can be used to simplify our development.

3. Injection of request parameters

In the STRUTS2 framework, the data submitted by the form is automatically injected into the property corresponding to the action object. It is the same as the IOC injection principle in the spring framework, which provides setter method injection for attributes through the Action object

Requirements:

The Name property of the form in the JSP corresponds to the setter method of the corresponding property in the action. The Setxxx () method must be provided for the action object that is to inject the property value, because the internal implementation of STRUTS2 is to automatically inject a value for the property according to the setter method provided in the JavaBean specification

Therefore, the property name of the property that is injected in the action generally is equal to the name value of the corresponding control in the form, and the property provides the GetXXX (), Setxxx () method

Domain Model Domainmodel

We use attributes with the same point like to encapsulate it, which is more structured and straightforward. The first way to inject request parameters can cause too much code in the action if there are too many parameters

Encapsulates some property information into a property of an entity object. The method of manipulating the Realm object, referencing an entity object in the Action object, and the parameter values of the HTTP request can be injected into the properties of the entity object, which I is the way struts2 provides Domainmodel

Note: When using the domain model, the Name property of the form space in the JSP should correspond to the objects in the action and the attributes in the bean, in the form of an object. Properties, such as: User.Name

 PublicClass user{PrivateString name; PrivateString password; Private intAge ;  Public voidSetName (String name) { This. name=name;}  PublicString GetName () {returnname;}  Public voidSetPassword (String password) { This. password=password;}  PublicString GetPassword () {returnpassword;}  Public voidSetage (intAge) { This. age=Age ;}  Public intGetage () {returnAge ;}} PublicClass useractionextendsactionsupport{Privateuser User;  Public voidSetUser (user user) { This. user=user;}  PublicUser GetUser () {returnUser;}  PublicString Execute ()throwsexception{return"Success"; }}<body> <s:form action= "useraction" method= "POST" > <s:textfield name= "user.name" label= "user name"/> < S:password name= "User.password" label= "password"/> <s:textfield name= "User.age" label= "Age"/> <s:submit value= "Register"/> </s:form></body>
View Code

Drive Model Modeldriven

In the domain model Domainmodel, although the Struts2 action object can invoke an entity object for related operations by directly defining a reference to the instance object, the required parameter must be the entity object corresponding to the specified parameter. For example on Li Zhong need to specify parameter name User.Name this form, a little inconvenient

The driver model does not need to specify the object reference to which the parameter belongs. In the Struts2 API, an interface named Modeldriven is provided, and the action object can obtain the specified entity object by implementing this interface, obtained by implementing the Modeldriven provided by the Getmodel () method, with the syntax in the following form: T Getmodel ();

Processing flow

Struts2 instantiates the Action object, determines whether the action object implements the Modeldriven interface, and if the interface is instantiated, calls Getmodel () to get the entity Object model and return it. You can use the properties of the object directly later.

 PublicClass user{PrivateString name; PrivateString password; Private intAge ;  Public voidSetName (String name) { This. name=name;}  PublicString GetName () {returnname;}  Public voidSetPassword (String password) { This. password=password;}  PublicString GetPassword () {returnpassword;}  Public voidSetage (intAge) { This. age=Age ;}  Public intGetage () {returnAge ;}} PublicClass useractionextendsActionsupportImplementsmodeldriven{Privateuser User; @Override PublicUser Getmodel () {return  This. User; }   PublicString Execute ()throwsexception{return"Success"; }}<body> <s:form action= "useraction" method= "POST" > <s:textfield name= "name" label= "user name"/> <s:pas Sword name= "password" label= "password"/> <s:textfield name= "age" label= "ages"/> <s:submit value= "register"/> </ S:form></body>
View Code

4. Invocation of method in action

In general, the Execute action defaults to its execute () method, but if all of the control-layer code is written in the Execute method, it is not particularly desirable, reusability, or difficult to modify.

So we want to be able to go the other way in action

static method invocation:

The action tag in Struts.xml has the method attribute, which allows you to specify the methods that are called when the action is entered, replacing the role of execute () with this method

Dynamic Method Invocation

Dynamic action (active action)

The process is done by requesting a specific method in the action object to implement the dynamic operation. The way to do this is to match the method in action by adding the request string (the method name) to the URL address of the forced action. Example: The Add method for/useraction!add request Useraction

STRUTS2 supports dynamic method calls by default, and if needed, you can set constants in Struts.xml:

Name= "Struts.enable.DynamicMethodInvocation" value= "false"/>

Application Demo for dynamic action (code not tested only):

main code, partial limitation Public classUseractionextendsactionsupport{PrivateString Info;  PublicString Add ()throwsexception{Info= "Add user Information"; return"Add"; }   PublicString Update ()throwsexception{Info= "Update user Information"; return"Update"; }    PublicString GetInfo () {returninfo; }    Public voidsetInfo (String info) { This. info=info; }}struts.xml:<struts> < PackageName= "MyPackage"extends= "Struts-default" > <action name= "useraction"class= "Com.action.UserAction" > <result name= "Add" >user_add.jsp</result> <result name= "Update" >user _update.jsp</result> </action> </ Package></struts>user_add.jsp:<body> <font color= "Red" > <s:property value= "info"/> </font></body>user_update.jsp:<body> <font color= "Red" > <s:property value= "info"/> </font></body>index.jsp:<body> <a href= "Useraction!add" > Add user </a> <br/> <a href= "useraction!update" > Update user </a ></body>
Demo

Configuration file for Struts2:

Struts-default.xml is located in the Struts2-core-2.3.24.jar. Org.apache.struts2 Package

Struts-plugin.xml in packages from various plug-ins provided by struts

Struts.xml Web App Default struts2 configuration file in src directory

Struts.properties Struts2 in the framework of the properties profile, also in the SRC directory

Web. XML You can also set some information for Struts2 in this file

Struts searches for information in the order from top to bottom, if a constant is declared before this declaration overwrites it

Package configuration for Struts2

Java-like packages for improved readability and simplified Java work

<package name= "user" extends= "struts-default" namespace= "/user" >

......

</package>

Properties of the package and description

Name declares the package names so that it is convenient to reference the package elsewhere, and this property must be

Extends is used to declare a contract, that is, its parent package.

namespace specifies the namespace, which is the path that the action under this package needs to access

Abstract declares a package as an abstract type (action is not defined in the package)

namespace settings

In Javaweb development, the web directory is usually divided into modules, the home page of the hired user can be defined in the "/user" directory, the Access address is "/user/index.jsp". The Struts2 namespace specifies the access path to an action, which is declared using the namespace attribute in the package declaration of the configuration file Struts.xml

<struts>   < package name= "book" extends= "struts-default" namespace= "/bookmanager" >     ... </Package ></struts>

To find the order of the action:

Now you specify the package and find it in the other packages in the same struts.xml, and then look in its parent bundle, and you can't find it. 404

Action-related configuration

The action in STRUTS2 is the role of a controller

class= "Com.action.UserAction" method= "save" >   <result>/success.jsp</result></ Action>

Attributes and descriptions of elements in action

Name is used to configure the URL address requested by the Action object

The class name of the action object specified by class

METHOD specifies which one to call when the action object is requested

Converter specifying the class of the action type converter

Using wildcards for simplified configuration

There are two wildcard characters for Struts2: * denotes 0 or more characters; \ denotes escape character

<struts>  <packageextends= "Struts-default" namespace= "/" >      class= " Com.action. {1} Action "method=" {2} ">         <result name=" Success ">/{2}.jsp</result>     </action>  </ Package ></struts>

Precedence of wildcard characters:

(1) If the Struts.xml has the corresponding action name. Even if it has other wildcard matches, it takes precedence over exactly the same.

For example, one action name is "User_add" and one is "user_*". Now, a request is "user_add.action". Then, it will first match "User_add". In fact, this is very well understood.

(2) If an action name corresponds to an action name of two wildcard characters, then you need to see who is in front of this configuration. It matches the one written in the front

For example, there is an action name of "*_*" and one is "user_*". Now, a request is "user_add.action". Well, it will first match the one written in the previous ...

Any action with "*" name priority is the same ... Not that the priority of bringing a "*" is more than two "*

"The high.

The development model of STRUTS2

1. Realize the interaction with SERVLETAPI

Some methods of Actioncontext objects:

public static Actioncontext GetContext ()

public object get (object key)

Public Map getsession ()

Public Map getapplication ()

The STRUTS2 provides a map type of request, session, and application, which can be obtained from the Actioncontext object. The Actioncontext object is located in the COM.OPENSYMPHONY.XWORK2 package, which is the context of the action execution, and its common API is as follows:

Instantiate Actioncontext: Use the GetContext () method of the Actioncontext object to get the instantiated object of the Actioncontext. GetContext () is a static method that can be called directly

Actioncontext Context=actioncontext.getactioncontext ();

Gets the request for the map type, using the Get () method of the Actioncontext object to get

Map Request=actioncontext.getcontext (). Get ("request");

The get session can also be obtained in Get (), but Actioncontext also deliberately reserved the way to get the session getsession ()

Application is similar to the session

Map session=Actioncontext.getcontext (). GetSession (); Map session1=actioncontext.getcontext (). Get ("session"); MAP Application=actioncontext.getcontext (). Getapplication (); Map Application1=actioncontext.getcontext (). Get ("Application");

Hand-hit struts knowledge points

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.