STRUTS2 Development Foundation

Source: Internet
Author: User

STRUTS2 Development Foundation

Struts2 uses interceptors to handle user requests, allowing the business logic controller to completely disengage from the SERVLETAPI.

1. Hello world!

Configure Web. xml

   <?xml version= "1.0" encoding= "UTF-8"? ><web-app id= "Webapp_9" version= "2.4" xmlns= "http://java.sun.com/xml/ Ns/j2ee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "         xsi:schemalocation=" http://java.sun.com/xml/ NS/J2EE http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">     <display-name>struts demo</ display-name>     <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>     <welcome-file-list>        <welcome-file> Index.html</welcome-file>    

Configure Struts.xml

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.3//en" "http://struts.apache.org/dtds/ Struts-2.3.dtd "> <struts> <package name=" Default "namespace="/"extends=" Struts-default ">         < Action name= "HelloWorld" class= "example. HelloWorld ">            <result name =" Success ">/WEB-INF/jsp/example/HelloWorld.jsp</result>        </ Action>     </package></struts>

Hello.java

Import com.opensymphony.xwork2.ActionSupport; public class Hello extends actionsupport {public    final Static String  MESSAGE = "Hello world!" ;     Private String msg;     Public String GetMessage () {        return msg,} public void setmessage (String msg) {this.msg = msg;} p Ublic String Execute () throws Exception {setmessage (MESSAGE); return SUCCESS;}}     
Deploying Struts2 apps to Tomcat
    1. Compiling the. java file
    2. Create a Web-inf folder under the Tomcat/webapps/appname folder
    3. Put the struts2 required package into the site/web-inf/lib,
    4. The compiled corresponding class file is placed in the/web-inf/classes/corresponding package directory according to the package structure.
    5. Put Struts.xml into the/web-inf/classes/folder
    6. Launch Tomcat, Access Localhost:protal/appname in the browser
Struts2 principle

When a Web container receives a request (HttpServletRequest), it passes the request to a standard filter chain. Next call the Filterdispatcher Core controller, and then it calls Actionmapper to determine which action to request. Actionmapper returns a Actionmaping object that collects the action details.

Next Filterdispatcher delegate control to Actionproxy,actionproxy call Configuration Manager (ConfigurationManager) to read configuration information (Struts.xml) from the configuration file. The Actioninvocation object is then created by reflection. Actioninvocation invokes the configured Interceptor (Interceptor) in turn before invoking the action.

Once the execution results return a result string, Actioninvocation is responsible for finding the result string corresponding to (result) and executing this result. Result invokes some template (JSP) to render the page, after which the Interceptor (Interceptor) is executed in reverse, processing the response (response).

Simply put, Strusts2 acts as a filter controller, as can be seen from Web. Xml.

2. STRUTS2 Configuration settings

Configuring the action is the core of the struts2 configuration.

(1) Packages and namespaces

STRUTS2 uses the package to organize the action, using the <package> tag in the XML configuration file to organize a package, and the action uses the <action> child element to complete.

<package name= "Default" namespace= "/" extends= "Struts-default" >

The <package> tag must specify the Name property, which is the unique identity of the access, the extends property specifies the inherited parent package, which can be configured in the parent package to integrate the action, interceptor, interceptor Stack, and so on. There is also an optional abstract property, abstract= "true", which means that the package cannot be configured with an action.

The namespace mechanism of the struts2 is used to avoid naming conflicts, the names of actions are not allowed under the same namespace, and duplicate names are allowed under different namespaces. The namespace property of the <package> tag is used to specify a namespace and does not allow space to be specified on a separate action.

If <package> does not specify the namespace property, it is the default namespace. Set <package namespace = "/" > specified as the root namespace. If the request is/space/*.actionweb, the container looks for the action in the Space namespace first, and if it is not found, it finds the action in the default namespace and an error occurs if it is still not found. If the request is/*.action, look for the action in the root namespace, which also illustrates the difference between the root namespace and the default namespace.

(2) Configure action

   <action name= "HelloWorld" class= "example. HelloWorld ">         <result name =" Success ">                 /web-inf/jsp/example/helloworld.jsp         </result > </action>     

The action must specify that the URL,STRUTS2 action handle the URL as namspace/actioname.action, or omit the. Action suffix.

Instead of directly generating a response as a logical controller, the action returns a string representing the result of the,<result> child label that will return the result corresponding to the physical view.

(3) Configuring constants

The STRUTS2 framework loads the Struts2 constants in the following order:

1. Struts-default.xml Struts2-core.jar

2.struts2-plugin.xml

3.struts.xml

4.struts.properties

5.web.xml

Constants that are loaded later overwrite the preceding constants.

For a modular configuration, Struts.xml can use the include tag to include additional XML configuration files:

<include file= "Example.xml"/>

(4) Configuration result 1. Result configuration

STRUTS2 uses <result> elements to configure processing results in Struts.xml. The result of processing can be divided into global result and local result according to scope, default as local result.

<action name= "HelloWorld" class= "example. HelloWorld ">         <result name =" Success ">                    /web-inf/jsp/example/helloworld.jsp         

The attributes to be configured for the <result> element include:

(1) Name: corresponds to the result string returned by the action, default is "SUCCESS"

(2) Type: Specifies the type of result

(3) Location: Specifies the actual view resource, using the string between <result></> as the view resource by default.

(4) Parse: whether to allow the use of OGNL expressions in <result>, the default is "true".

2. Result type

<result-type> can be customized in XML, and the commonly used result-type are defined in Struts-default.xml.

(1) Dispatcher:

Dispatcher is the result type used to specify the JSP view, which defaults to this type if the default type.

(2) PlainText:

The plaintext is used to return the source code of the view in plain text mode. The plaintext result type can specify the following parameters:

Loacation: Specifying actual view Resources

CharSet: Specifying a character Set

(3) redirect

Dispatcher returns the view resource using request forwarding, REDIRECT returns the view resource using redirection. The redirect type invokes the Httpservlet.sendredirect method to redirect, and this method will re-establish a request, and the data in the original request will be lost.

The redirect mode allows configuration of the loaction and parse two properties.

(4) Redirectaction

The redirectaction type is similar to redirect and generates a new request. The difference is that Redirectaction uses Actionmapperfactory's actionmapper to redirect the request to another action.

Redirect needs to specify namespace and ActionName to specify the namespace and ActionName of the target action.

3. Global results

<result> is used to configure local results, only valid for the action it belongs to. <globla-result> tags are used to configure global results and are valid for all ation.

<global-results>            <result name= "error" >/WEB-INF/jsp/error.jsp</result> </global-results >

Matches local results when matching results, and matches global results when local results do not match.

3. Develop action (1) to implement action

STRUTS2 does not require the action class to implement any interfaces or inherit any classes, but for standardized programming, STRUTS2 provides an action interface that defines the canonical action class and provides it with a Actionsupport implementation class ( Com.opensymphony.xwork2.ActionSupport;), typically we inherit the Actionsupport class and override the public String execute (void) method. Actionsupport defines the data checksum method for obtaining internationalized information, and if you omit the class attribute in the Struts.xml action configuration, you use Actionsupport as the implementation class.

The Execute method returns a string representing the processing result and maps it to a physical view based on the configuration in the XML. STRUST2 defines 5 standard strings: "SUCCESS", "ERROR", "LOGIN", "INPUT", "NONE", and you can still use a custom string as the result of processing.

(2) Accessing the servlet API

1. Using Actioncontext

Struts2 's action is no longer coupled to the Servlet API, but provides a way to access the Servlet API. STRUTS2 provides the Actioncontect class and accesses the servlet API through this class.

(1) Actioncontext CTX = Actioncontext.getcontext ();

The GetContext () method can obtain an Actioncontext instance.

(2) Map session = Ctx.getsession ();

Gets the session instance.

(3) Map sctx = ctx.getapplication ();

Get ServletContext instances

(4) void Setsession (Map session);

Set session.

(5) void Setapplication (MAP application)

Set the application.

(6) Map getparameters ()

Equivalent to the Httpservletrequest.getparametermap () method, which gets the requested parameter.

(7) object get (Object key)

Equivalent to the Httpservletrequest.getattribute (String key) method.

2. Using Servletactioncontext

Servletactioncontext provides a static method to obtain the corresponding object.

(1) Obtain the PageContext object.

static PageContext getpagecontext ()

(2) Obtain the HttpServletRequest object.

static HttpServletRequest getrequest ()

(3) Obtain the Httpservletreponse object.

static Httpservletreponse getreponse ()

(4) Obtain the ServletContext object.

static ServletContext Getservletcontext ()

3. Implement the Aware series interface

(1) Servletresponseaware

The class that implements the interface for this interface can directly access the HttpServletResponse object, but must implement the Setservletresponse () interface.

Class Myaction implements Action, Servletresponseaware {private httpservletresponse response; public void Setservletresponse (httpservletresponse response) {this.response = response;       

(2) Servletrequestaware

Similar to Servletresponseaware, classes that implement this interface can access the HttpServletRequest object as long as the implementation method:

Public void Setservletrequest (HttpServletRequest request)

(3) Servletcontextaware

Similar to Servletresponseaware, classes that implement this interface can access the Httpservletcontext object as long as the implementation method:

Public void Setservletcontext (Httpservletcontext request)

STRUTS2 Development Foundation

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.