Decoupling struts2 actions from servletapi

Source: Internet
Author: User

Unit testing is an important part in development.
When programmers write code, the corresponding unit tests should also be complete; otherwise, your code will be unconvincing.
Struts2 decouples action from servlet APIs, making unit testing very easy.
For exampleHttpservletrequest object, It is composedTomcat containerProvided to us, we cannot generate it ourselves
If the action is filled with servletapi, even if there is only one, then in the general senseJUnitUnit tests cannot be performed.
If servletapi is coupled in the action, you can use the ApacheCactusTest it, which is a little effort-consuming.
You can also useMockIt is a simulated servlet API-related object.
Then, the simulated object is used to replace the objects generated in the container to access the application.
The struts2 action hasBreakWith servletapi, you can directly use JUnit for testing without using either of the two methods.

Test action in struts2 and struts1.x
Struts1.x actionDependent on servletapiFor exampleHttpservletrequest and httpservletresponseObject
These classes are combined with containers, so they mustStart Tomcat serverThen you can obtain the objects in the container.
So it is troublesome to test. WhileApacheProvides a project that can be bundled to eclipse for independent testing.
It simulates a seriesHttpservlet objectAfter using it, you canLeave TomcatIndependent Test
Struts2 actionContainer independent, It has nothing to do with the container, so canRemove from ContainerPerform separate tests
In other words, we can directly writeMain ()Method To test, this is OK
InStruts1.xIs unimaginable, it must be eitherStart TomcatThen perform the test, orPlugin installationTest again

Struts2 is not coupled with any servlet API
In this way, you can easily test the action without relying on Web containers such as Tomcat.
Struts2 provides usThree methodsSo that we can easily obtain the servlet API
Actioncontext
Servletactioncontext
Implement specific Interfaces
BecauseCom. opensymphony. xwork2.actioncontextAPIS already associated with ServletCompletely decoupledNow
SoActioncontext is recommended.,Followed by servletactioncontext,The least recommended Interface

The first class is com. opensymphony. xwork2.actioncontext.
First passActioncontext classStaticGetcontext ()Method to obtainAn actioncontext instance
Then you can use this instance to call many of its methods to obtain some servlet APIs.
Public object Get (Object key)Method, which is equivalentHttpservletrequest. getattribute ()
Public void Put (Object key, object value)CorrespondingHttpservletrequest. setattribute ()
Public Map <string, Object> Getparameters ()CorrespondingHttpservletrequest. getparametermap ()
Public Map <string, Object> Getsession ()Method correspondenceJavax. servlet. http. httpsession
Session. Put (Object key, object Value)Corresponding to the servlet ProgrammingHttpsession. setattribute (...)
That is to say,ActioncontextThreeMapTypeRequest, session, ApplicationObject
One advantage of actioncontext is that it has converted the underlying servlet, for example, it has converted the session into a map
In this way, struts2 can be detached from the servlet container during the test.Simple JUnit Testing

Org. Apache. struts2.servletactioncontext Class 2
Servletactioncontext. Getrequest ()CorrespondingJavax. servlet. http. httpservletrequest
Servletactioncontext. Getresponse ()CorrespondingJavax. servlet. http. httpservletresponse
Servletactioncontext. Getservletcontext ()CorrespondingJavax. servlet. servletcontext
All of its methods areStatic. In addition, the obtained servletcontext object is equivalentApplication
Because its lifecycle is the same as that of the application, it is effective as long as the server is not closed.
ServletactioncontextAvailableBind to containerOfRequest, response, servletcontextObject
All the results here are not map objects. Therefore, during testing, you mustStart Tomcat server

The third type is the org. Apache. struts2.util. servletcontextaware interface.
It has only oneVoid setservletcontext (Javax. servlet. servletcontext Context)Method
The servletcontext obtained through this method is equivalent to the application, and both have the same lifecycle.
And the org. Apache. struts2.interceptor. servletrequestaware Interface
There is alsoVoid setservletrequest (Javax. servlet. http. httpservletrequest request)Method
And the org. Apache. struts2.interceptor. servletresponseaware Interface
There is alsoVoid setservletresponse (Javax. servlet. http. httpservletresponse response)Method
The usage and Sample Code are as follows:
In this case, you need to setCoupling with servlet containersOfHttpservletrequest typeOfRequest member variable
When the execution is completeSetservletrequest ()Method.Httpservletrequest ParametersAssigned
This method is composedAutomatic struts2 callObviously, this is a very, very typicalDependency InjectionDi]
The HTTP servletrequest object automatically generated by the container by struts2SetTo the variables in our application
In this way, the request of the member variable becomes the httpservletrequest object generated by the container.
Next we canNormal useRequest. The method is the same as that in servlet.
Public class decoupleaction implements servletrequestaware {<br/> private httpservletrequest request; <br/> Public void setservletrequest (httpservletrequest arg0) {<br/> This. request = arg0; <br/>}< br/>}

Supplement org. Apache. struts2.interceptor. requestaware Interface
The sample code is as follows:
Public class decoupleaction implements requestaware, sessionaware, applicationaware {<br/> map request; <br/> map session; <br/> map application; <br/> Public void setrequest (MAP arg0) {<br/> This. request = arg0; <br/>}< br/> Public void setsession (MAP arg0) {<br/> This. session = arg0; <br/>}< br/> Public void setapplication (MAP arg0) {<br/> This. application = arg0; <br/>}< br/>}
Here we useIOC ModeTo grant the three map variable initialization permissions to the caller, that is, the container
The container will automatically use these threeSetxxx ()ThreeMap variableFrom outsideInjectionCome in
In action, we do not need to create a new map object or perform any initialization operations.
Then you can directly useRequest, session, ApplicationThree objects

Summary
And servlet containersDecouplingOfNon-IOCMethod:Com. opensymphony. xwork2.actioncontext class
And servlet containersDecouplingOfIOCMethod:Requestaware, sessionaware, and applicationaware Interfaces
And servlet containersCouplingOfNon-IOCMethod:Org. Apache. struts2.servletactioncontext class
And servlet containersCouplingOfIOCMethod:Servletrequestaware and servletresponseaware Interfaces

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.