Detailed description of struts2 basic configurations

Source: Internet
Author: User

Detailed description of struts2 basic configurations

I. Working Principle of struts2(Summary by netizens, all requests are handled in a thousand times)

 

1. The client initializes a request pointing to a Servlet container (such as Tomcat ).
2. This request goes through a series of filters (these filters have an optional Filter called ActionContextCleanUp, which is very helpful for the integration of Struts2 and other frameworks, such as SiteMesh Plugin)
3. FilterDispatcher is called. FilterDispatcher asks ActionMapper to determine whether to call an Action.
4. If ActionMapper decides to call an Action, FilterDispatcher submits the request processing to ActionProxy.
5. ActionProxy asks the framework Configuration file through Configuration Manager and finds the Action class to be called.
6. ActionProxy creates an ActionInvocation instance.
7. The ActionInvocation instance uses the naming mode for calling. Before and after the Action is called, the call of the relevant Interceptor (Intercepter) is involved.
8. Once the Action is executed, ActionInvocation is responsible for finding the corresponding return result based on the configuration in struts. xml. The returned result is usually a JSP or FreeMarker template to be represented (but not always, or another Action chain. You can use the tag inherited from the Struts2 framework in the Process of representation. ActionMapper needs to be involved in this process

All objects (actions, Results, Interceptors, etc.) in the above process are created through ObjectFactory.

 

 

Ii. Basic struts2 Configuration

2.1 struts. xml configuration file details

<Struts> <! -- Use in development mode to print more detailed error information --> <constant name = "struts. devMode" value = "true"/> <! -- Internationalization --> <constant name = "struts. i18n. encoding" value = "UTF-8"/> <! -- Allow ognl to access static methods --> <constant name = "struts. ognl. allowStaticMethodAccess" value = "true"/> <! -- This attribute specifies the request suffix to be processed by struts2. The default value is action, that is, all matches *. all action requests are processed by struts2. If you need to specify multiple request suffixes, separate them with commas (,). --> <constant name = "struts. action. extension "value =" action "/> <! -- Sets whether the browser caches static content. The default value is true (used in the production environment). It is best to disable it during development --> <constant name = "struts. serve. static. browserCache "value =" false "/> <! -- If the struts configuration file is modified and the system automatically reloads the file, the default value is false: Do not reload --> <constant name = "struts. configuration. xml. reload "value =" true "/> <! -- Default view topic --> <constant name = "struts. ui. theme" value = "simple"/> <! -- When integrating with spring, specify that spring is responsible for managing the creation of action objects --> <constant name = "struts. objectFactory" value = "spring"/> <! -- This attribute sets whether struts2 supports dynamic method calls. The default value is true. --> <constant name = "struts. enable. DynamicMethodInvocation" value = "false"/> <! -- Size limit of uploaded files --> <constant name = "struts. multipart. maxSize" value = "10701096"/> <! -- Import file --> <include file = "cn/qjc/action/login. xml "> </include> <include file =" cn/qjc/action/demo/demo01.xml "> </include> <include file =" cn/qjc/interceptor. xml "> </include> </struts>

 

Struts2 configuration file loading sequence

A, default. properties: struts2-core **. jar org. apache. struts package (programmers can only see)

B, struts-default.xml: struts2-core **. jar (programmers can only see)

C. struts-plugin.xml: in the jar package of the plug-in (the programmer can only see)

D. struts. xml: The top of the application build path. Custom Struts configuration file (Recommendation)

E. struts. properties: The top of the application build path. Programmers can write (not recommended)

F. web. xml: Specify the parameter When configuring the filter. Programmers can write (not recommended)

Note: The order is fixed. The subsequent configuration will overwrite the previous configuration with the same name.

 

Loading struts. xml

Note:

1. Three configuration files struts-default.xml, struts-plugin.xml, struts. xml are loaded at startup.

2. If the three files have the same items, they will be overwritten later.

3. the struts. xml file must be placed under src to be found.

2.2 package Elements

Meaning: submodule Development

Attribute:

Name: required. The configuration file must be unique. Is a name.

Extends: Specifies the parent package. The configuration content in the parent package is inherited. Generally, you need to inherit a package called struts-default directly or indirectly (in the struts-default.xml configuration file ).

If the package is not inherited, the core functions in Struts2 will not be available.

Abstract: whether it is an abstract package. A package without any action sub-elements can be declared as an abstract package.

Namespace: Specify the namespace. It generally starts. Action access path in the package: namesapce + action name. If namespace = ", this is the default namespace, which is the same as not writing this attribute.

 

2.3 action configuration

Purpose: Define an action.

Attribute:

Name: required. Action name. The user initiates a request. It must be unique in the package.

Class: Specifies the full name of the category class. The framework is instantiated through the reflection mechanism. The default value is com. opensymphony. xwork2.ActionSupport.

Method: Specifies the action methods in the actions class. The framework executes this method. The default value is execute ().

<! -- Configure global view: no local view is available for access actions, find the global View --> <package name = "default" extends = "struts-default" abstract = "true"> <global-results> <result name = "success">/ WEB-INF/login/success. jsp </result> </global-results> </package> <package name = "login" namespace = "/user" extends = "default"> <action name = "login "class =" cn. qjc. action. login. login "method =" login "> <! -- Type the default dispatcher indicates request forwarding --> <result name = "success" type = "dispatcher">/WEB-INF/login/success. jsp </result> <result name = "error">/WEB-INF/login/error. jsp </result> </action> </package>

Iii. Action)

3.1 three methods for compiling the category class:

A. POJO (Plain Old Java Object) is a common JavaBean.

/*** Method 1 for compiling the category class: General javaBean * @ author qjc */public class Demo1Action {public String seyHello () {System. out. println ("pipeline class executed"); return "success ";}}

B. Implement the com. opensymphony. xwork2.Action Interface

/*** Method 2: implement the Aaction interface * @ author qjc */public class Demo2Action implements Action {@ Override public String execute () throws Exception {System. out. println ("executed class"); return SUCCESS ;}}

C,Inherit from com. opensymphony. xwork2.ActionSupport (recommended)

Meaning: provides some basic functions. For example, verification and international message prompts.

/*** Method 3: Inherit the ActionSupport class * @ author qjc */public class Demo3Action extends ActionSupport {}

3.2 ActionSupport usage

In the struts framework, an ActionSupport class is prepared for source code analysis:

Code snippet 1:

public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {

Code Segment 2:

/*** A default implementation that does nothing an returns "success ". * <p/> ActionSupport is a default Action implementation, but only the success * Subclasses shoshould override this method to provide their business logic is returned. * <p/> The subclass must overwrite the entire method and write the corresponding logic in this method * See also {@ link com. opensymphony. xwork2.Action # execute ()}. ** @ return returns {@ link # SUCCESS} * @ throws Exception can be thrown by subclasses. */public String execute () throws Exception {return SUCCESS ;}

Code snippet 3:

    public static final String SUCCESS = "success";

Note:

1. The code segment indicates that ActionSupport also implements the Action interface (previously written classes implement the Action interface)

2. code snippet 2 indicates that if a programmer writes his own action that inherits ActionSupport, he/she needs to overwrite the execute method again.

3. success is returned by default;

Therefore, you can also write the following in the configuration file:

<action name="actionSupprotAction">    <result name="success">/baseconfig/successActionSupport.jsp</result></action>

We can see that the action tag does not have the class property, in the struts-default.xml,

<default-class-ref class="com.opensymphony.xwork2.ActionSupport" />

Note:

If the class attribute is not written in the action tag. According to the above configuration file, struts2 will enable the ActionSupport class. Therefore, the class attribute in the action tag can be left empty.

 

Iv. Result type

1. Each action method returns a value of the String type, and the value returned by a single struts request is determined by this value.

2. In the configuration file, each action element must have a result element, and each result corresponds to the return value of an action.

3. Result has two attributes:

Name: name of the result. It is the same as the return value in action. The default value is success;

Type: Response result type. The default value is dispatcher.

In the struts-default.xml file, as shown below

<result-types>    <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>        <result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>        <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>        <result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>        <result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>        <result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>        <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>        <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>        <result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>        <result-type name="plainText" 

 

Note:

1. From the above we can see that there are 10 types in total

2. The default type is ServletDispatcherResult.

3. The result type can be any of the 10 result types.

  

4.1 dispatcher type:

The dispatcher type is the most common result type and is also the default result type of the struts framework.

The configuration file can be written in either of the following ways:

Method 1: <result name = "success">/resulttype/successDispatcher. jsp </result> Method 2: <result name = "success"> <param name = "location">/resulttype/successDispatcher. jsp </param> </result>

The following figure shows the origin of location:

4.2 redirect type:

This type of result is opposite to the dispatcher type. The dispatcher result type refers to the request forwsrd (forward) to the specified JSP resource. The redirect result type means the request redirect (redirect) to the specified view resource.

The main difference between redirect and dispatcher is the difference between forwarding and redirection: Redirection will lose all request parameters, request attributes, and of course the Action processing result.

Note:

When using redirect type results, you cannot redirect to any resources under the/WEB-INF/path, because redirection is equivalent to sending a request again, and the WEB-INF/path of the Web application is protected.

4.3 redirectAction type: 

This type of result is very similar to the redirect type. In the same way, a new request is regenerated, but the difference with redirect is that redirectAction uses ActionMapper provided by ActionMapperFactory to redirect requests.

That is, redirect the result type to action.

Two parameters are acceptable.

A) actionName: action name

B) namespace: namespace

Method 1

<result name="success" type="redirectAction">resulttype/redirectactionAction.action</result>

Method 2

<Result name = "success" type = "redirectAction"> <! -- ActionName: The request action path namespace: If this parameter is not specified, the request action path is used by default. If this parameter is specified, the path will be re-assigned --> <param name = "actionName"> resulttype/redirectactionAction. action </param> </result>

4.4 Other Types

Freemarker: Used to forward data to another freemarker template. (Static Page)

Velocity: Used to forward data to another velocity template.

Httpheader: the message header used to output the http protocol.

Xslt: XML-related styles

Redirect: Used to redirect to another JSP page.

RedirectAction: Used to redirect to another action.

Stream: used for downloading files. File upload and download)

PlainText: displays pages in plain text. Output source code.

4.5 custom type

Step for customizing the result type

Take the Random verification code image as an Example

A. Compile a class to directly or indirectly implement the com. opensymphony. xwork2.Result interface. Generally, it inherits the org. apache. struts2.dispatcher. StrutsResultSupport class.

/*** Use the custom result set to load the Verification Code * @ author qjc */public class Demo02 extends StrutsResultSupport {private int width = 120; private int height = 80; private int codeCount = 4; private int lineCount = 100; @ Override protected void doExecute (String finalLocation, ActionInvocation invocation) throws Exception {// ValidateCode vc = new ValidateCode (width, height, codeCount, lineCount); BufferedImage image = vc. getBuffImg (); // output HttpServletResponse response = ServletActionContext. getResponse (); ImageIO. write (image, "jpeg", response. getOutputStream ();} // getter and setter are omitted here...
}

 

B. Declare the result type before using

<! --
Custom result set
--> <Package name = "p3" extends = "struts-default"> <result-types> <! -- Result type definition --> <result-type name = "captcha" class = "cn. qjc. action. demo. demo02 "> </result-type> </result-types> </package>

 

C. Use

<Action name = "captcha"> <! -- Use the custom result type: captcha --> <result name = "success" type = "captcha"> <param name = "width"> 200 </param> </result> </action>

Page writing

<Body> <form action = "$ {pageContext. request. contextPath}/user/login. action "> username: <input name =" username "> <br> password: <input type =" password "name =" password "> <br> Verification Code: <input name = "code" size = "4">  <br> <input type =" submit "value =" Logon "> </form> </body>

 

V. Action prototype

In servlet, a servlet has only one object, that is, the servlet is a singleton mode. If you write a set in the servlet attribute, you need to consider the thread security issue.

However, this is not the case in the struts2 framework, and action is multi-sample. That is to say, the action in struts2 will instantiate an object once it is accessed. In this way, there is no thread security problem. This is also a benefit of the struts2 framework.

You can write a class as follows:

package cn.qjc.struts2.action.moreinstance;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class MoreInstanceAction extends ActionSupport{    public MoreInstanceAction(){        System.out.println("create new action");    }    public String execute(){        System.out.println("more instance action");        return SUCCESS;    }}

The configuration file is:

<struts>    <package name="moreinstance" namespace="/moreinstance">        <action name="moreinstanceAction"            class="cn.qjc.struts2.action.moreinstance.MoreInstanceAction">        </action>    </package></struts>

Http: // localhost: 8080/struts2/moreinstance/moreinstanceAction. action path twice in the constructor. If "create new action" is output twice in the constructor, the object is created twice.

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.