STRUTS2 Basic-Simple Java class implementation action Controller

Source: Internet
Author: User

In Strut2, an action can not inherit any special class or implement any special interface, you can write just one plain Java class as the action class, as long as the class contains a non-parametric public method that returns a string! In actual development, the Actionsupport class (which inherits the action interface) is usually inherited to write the action request processing class. The following is an example of a common Java class as the Actoin class:

Project structure

1. Web. XML configuration

1<?xml version= "1.0" encoding= "UTF-8"?>2<web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee"3Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee5http//java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">6<welcome-file-list>7<welcome-file>index.jsp</welcome-file>8</welcome-file-list>9 Ten<filter> One<filter-name>StrutsPrepareAndExecuteFilter</filter-name> A<filter-class>org.apache.struts2.dispatcher.ng.filter.Strutsprepareandexecutefilter</filter-class> -</filter> -  the<filter-mapping> -<filter-name>StrutsPrepareAndExecuteFilter</filter-name> -<url-pattern>/*</url-pattern>//interception of all requests

<!--<url-pattern>*.action</url-pattern>-->//interception of requests ending with. Action

 -     </filter-mapping></web-app>

2. Action Class

1  Packagecn.test.action;2 3  Public classuseraction {4     5      PublicString Login () {6         return"Success";7     }8     9      PublicString Register () {Ten         return"Success"; One     } A  -}

3.struts.xml Configuring the Action class

1<?xml version= "1.0" encoding= "UTF-8"?>2<!DOCTYPE Struts public3"-//apache software foundation//dtd Struts Configuration 2.3//en"4"Http://struts.apache.org/dtds/struts-2.3.dtd" >5<struts>6< PackageName= "user" namespace= "/user"extends= "Struts-default" >7<action name= "Login"class= "Cn.test.action.UserAction" method= "Login" >8<result>/login.jsp</result><!--result does not write the Name property, the default is success--9</action>Ten<action name= "Register"class= "Cn.test.action.UserAction" method= "register" > One<result>/register.jsp</result> A</action> -</ Package> -  the</struts>

4. JSP page, no substantive code, just as display STRUTS2 request processing display

1<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8"%>2<%3String Path =Request.getcontextpath ();4String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";5%>6 7<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >89Ten<base href= "<%=basePath%>" > One<title>my JSP ' login.jsp ' starting page</title> A -    -<body> theThis is my login JSP page. <br> -</body> -
1<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8"%>2<%3String Path =Request.getcontextpath ();4String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";5%>6 7<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >89Ten<base href= "<%=basePath%>" > One<title>my JSP ' register ' starting page</title> A -    -<body> theThis is the My Register JSP page. <br> -</body> -

5. Deploy and Access:

http://localhost:8080/strutsstu0/user/login results are as follows:

Access Http://localhost:8080/strutsstu0/user/register results are as follows

If Url-pattern is configured as <url-pattern>*.action</url-pattern> in Web. XML, then the access is appended with the. Action : http://localhost:8080/strutsstu0/user/login.action, the results are as follows:

6. Struts2 Execution Process Analysis:

(1) Web. xml

The STRUTS2 framework is based on the MVC pattern, and the core of the MVC pattern framework is that the controller handles all requests uniformly. The STRUTS2 controller Strutsprepareandexecutefilter is played by the filter in the Servlet API,

When the Web container receives the request, it gives the request to the filter configured in XML. Strutsprepareandexecutefilter, which initializes the framework and processes all requests. (Any Web application is built based on the request/response pattern, regardless of which MVC framework is used, without the configuration of the XML file.) The MVC framework can truly fuse with Web applications only if the Web. xml file is configured in an application. )

Strutsprepareandexecutefilter can contain some initialization parameters, and if no initialization parameters are configured, theStruts2 framework loads Struts-default.xml, Struts-plugin.xml and Struts.xml

(2) Action

STRUTS2 Framework China, the controller consists of two parts: the core controller filter is used to intercept user requests, handle requests, business controller, call the corresponding model class to implement business processing, return results

In the Struts.xml configuration file, a request URI is mapped to an action class, and the framework uses the action class to process the request when a request matches the name of an action.

<package name= "User"namespace= "/user"extends= "Struts-default" > 7 <actionname= "Login"  class= "cn.test.action.UserAction"  method= "Login" > 8 <result>/login.jsp</result> <!--result does not write the Name property, the default is success-9 </action>10 <action name= "register" class= "Cn.test.ac tion.     Useraction "method=" register ">11 <result>/register.jsp</result>12 </action>13 </package>

Configuration Explanation:
The STRUTS2 Framework organizes the action result, among other things, into a logical unit called package, simplifying maintenance and improving reusability, each containing the definition of the action result to be used. Packages in Struts2 can be "inherited"

A package that has already been defined, inheriting all definitions of the original package (including the configuration of action result, etc.) and can add the location of its own package.

The package element is used in struts.xml to define packages, where:

The name property is mandatory and unique, and is used to specify the names of the packages (referenced by other packages)

The extends property Specifies the package to be extended, typically inheriting the Struts-default package By default (this package is defined by the STRUTS2 framework love, which configures a large number of commonly used STRUTS2 features. Without these features, simply getting the request data in the action cannot be completed. )

The namespace property is optional, which defines the namespace of the action in the package, and if the property is not set, the action is placed in the default namespace. The STRUTS2 framework uses the name of the action and the namespace of the package it is in to identify an action, the default namespace is expressed as "", or you can use "/" to define a root namespace, which differs from the other.  When Struts2 receives a request, the framework says that the URL is divided into namespace and the action name, and the framework first finds the action in the namespace namespace, and then finds it in the default namespace if it is not found.

For example, if the request URL is/mysapce/somespace/some.action, the framework will first look for the some.action under the/mysapce/somespace namespace, and if not found, the framework will go to the default namespace to find

Example: Add a default namespace to the Struts.xml configuration file for the above project, the Name property of the action element is still called login, modify the jump page to index.jsp

1 <!--default namespaces-2     < packageextends= "Struts-default" >3          Class= "Cn.test.action.UserAction" method= "Login" >4             <result>/ Index.jsp</result>5         </action>6     </Package >

Add index.jsp page

1<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8"%>2<%3String Path =Request.getcontextpath ();4String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";5%>6 7<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >89Ten<base href= "<%=basePath%>" > One<title>my JSP ' register ' starting page</title> A -    -<body> theThis is myIndex JSP page. <br> -</body> -

Then redeploy and access Http://localhost:8080/strutsstu0/login with the following result, that is, the action requested at this time is the default root namespace, and the page jumps to the index.jsp

(3) Result

When the action class finishes processing the user request, it returns a processing result, which is a simple string that the framework chooses the corresponding result from, and therefore makes the string a logical view name, represented by the Name property of the result element. The value of the result element (the contents of <result> </result>) is used to specify the location of the physical view resource for this logical view, and it is important to note that the logical view name is only associated with the physical view resource in order to function. Therefore, the correspondence between the two must be configured.

The configuration of the result element consists of two parts, the location of the actual resource represented by result and the result name, and the type of result, set by the Type property of the result element

The Name property of the result element is not written, the default is "Success", the type attribute is not written, the default is "dispatcher",<result >/index.jsp</result> is equivalent to

<result name= "Success" type= "Dispatcher" >/index.jsp</result>

Summary: This process of STRUTS2 application is performed according to the request/response process, as shown in:

Overall there are three steps:

(1) When the Web container receives the request, the request is handed over to the core controller of the STRUTS2 framework configured in XML Strutsprepareandexecutefilter

(2) The Action (business controller) that the request corresponds to is determined by the Strutsprepareandexecutefilter

(3) The framework selects the corresponding result from the core controller strutsprepareandexecutefilter based on the resulting string returned by the action, presenting the result to the user

Attention:

(a) Action acts as a business controller and is only responsible for returning results, not associated with views, and the advantage is that when the view changes, there is no need to modify the code of the Action class, only the configuration file can be modified

(b) When strutsprepareandexecutefilter invokes the corresponding view, the default is to jump to the specified JSP page by forwarding (ForWord)

<result name= "Success" type= "Dispatcher" >/index.jsp</result>

The type value can be:

(1) Dispatcher:

The default result type, STRUTS2 internally uses the feature Servlet API's requestdispathcer to forward requests to the specified view resource, request data that is contained in China for the year still exists

(2) Redirect:

Request redirection, that is, the server tells the request that you have to re-request the specified view resources. The Sengredirect () method of the HttpServletResponse object used internally by the redirect result type redirects the request to the specified URL, which means that the request contains parameters, attributes, The action instance and the properties that are encapsulated by the action are all lost

(3) Redirectaction:

Redirects to a different action. is the Sengredirect () that uses the HttpServletResponse object Method redirects the request to another action. That is, when request processing is complete and you need to continue processing the request in another action, you can use Redirectaction to redirect to the specified action (the request parameter is also lost due to redirection)

7.struts Configuration file Load path

Take native Tomcat deployment as an example: you can see the deployment path as follows:

Entering the strutsstu0\web-inf\classes directory, you can see the struts.xml configuration file, Struts2 allows a profile to be split into multiple profiles, but the default is to load only web-inf\ Struts.xml files in the classes directory

The split configuration file needs to be introduced in Struts.xml, for example: <include file = "Struts-user.xml" >

STRUTS2 Basic-Simple Java class implementation action Controller

Related Article

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.