Java programmers go from stupid birds to cainiao (forty-three) to discuss struts2 (6) Getting servletapi and encapsulating form data

Source: Internet
Author: User

This article is from: Cao shenghuan blog column. Reprinted please indicate the source:Http://blog.csdn.net/csh624366188 

 

I. Three methods for obtaining the servletapi

In traditional web development, httpservletrequest, httpsession, and servletcontext in servlet APIs are often used. The struts 2 framework allows us to directly access and set the data of action and model objects, which reduces the use requirements for the httpservletrequest object and reduces the dependence on the servletapi, this reduces the Coupling Degree with servletapi. But in some applications, we can
Objects such as httpservletrequest can be accessed in the action, so sometimes we have to narrow down the relationship between struts2 and servletapi, but struts2 also has a method to minimize coupling, next, let's take a look at three methods to obtain the servletapi in struts2:

 

1. servletapi solution (1) obtain the map object:

To avoid coupling with Servlet APIs and facilitate unit tests for Action classes, Struts 2 encapsulates httpservletrequest, httpsession, and servletcontext and constructs three map objects to replace these three objects, in the action, the map objects corresponding to httpservletrequest, httpsession, and servletcontext are directly used to save and read
Data. You can use the com. opensymphony. xwork2.actioncontext class to obtain the three objects. Actioncontext is the context of Action execution. It stores many objects, such as parameters, request, session, application, and locale. The method for obtaining a map object through the actioncontext class is:

Actioncontextcontext = actioncontext. getcontext (); -- get the context maprequest = (MAP) Context of the Action execution. get ("request"); -- get the map object mapsession = context of httpservletrequest. getsession (); -- get the map object mapapplication = context of httpsession. getapplication (); -- get the map object of servletcontext

The data stored in actioncontext can be obtained from the request object. The secret lies in the org. Apache. struts2.dispatcher. strutsrequestwrapper class in struts 2. This class is
The packaging class of httpservletrequest, which overrides the getattribute () method (this method is required to obtain the attribute of the request object on the page). In this method, it first searches for the attribute in the request object, if no data is found (if you cannot find the data stored in actioncontext), search in actioncontext. This is why the data stored in actioncontext can be obtained from the request object.

2. Obtain the servletapi through IOC (control inversion)

The action class also has another decoupling method for obtaining the servletapi, which means we can enable it to implement some specific interfaces, let the struts2 framework inject request, session, and application objects to the action instance at runtime. This method is the IOC (control inversion) method. The corresponding three interfaces and their methods are as follows:

public class SampleAction implementsAction,RequestAware, SessionAware, ApplicationAware{private Map request;private Map session;private Map application;@Overridepublic void setRequest(Map request){this.request = request;}@Overridepublic void setSession(Map session){this.session = session;}@Overridepublic void setApplication(Map application){this.application = application;}}

The servletrequestaware interface and the servletcontextaware interface do not belong to the same package. The former is in the org. Apache. struts2.interceptor package, and the latter is in the org. Apache. struts2.util package, which is confusing.

 

3. access method coupled with Servlet API

Directly accessing the servlet API will coupling your action with the servlet environment. We know that the objects httpservletrequest, httpservletresponse, and servletcontext are constructed by the servlet container, binding with these objects requires a servlet container during testing, which is not convenient for unit testing of action. But sometimes, we do need to directly access these objects, so of course we need to complete the task. To directly obtain the httpservletrequest and servletcontext objects, you can use org. Apache. struts2.
Servletactioncontext class, which is a subclass of actioncontext, defines the following two static methods in this class:

1. Get the httpservletrequest object:

Public static httpservletrequestgetrequest ()

2. Get the servletcontext object:

Public static servletcontextgetservletcontext ()

In addition, the servletactioncontext class provides methods to obtain the httpservletresponse object, as follows:

Public static httpservletresponsegetresponse ()

The servletactioncontext class does not provide a method to directly obtain the httpsession object. The httpsession object can be obtained through the httpservletrequest object.

In addition to the above method call to obtain the httpservletrequest and servletcontext objects, you can also call the get () method of the actioncontext object and pass the servletactioncontext. http_request and servletactioncontext. servlet_context key values to obtain httpservletrequest and
The servletcontext object is the same. You can also pass the servletactioncontext. Http _ response key value to the get () method of actioncontext to obtain the httpservletresponse object.

 

Conclusion: we can see from the above three methods that the three methods for obtaining the servletapi are similar. Generally, we recommend that you use the first method to obtain the httpservletrequest and servletcontext objects, this is simple and clear, and reduces the Coupling Degree with servletapi, which facilitates unit testing.

Ii. struts2 encapsulate Request Parameters in three ways

In struts2 development applications, we may often need to obtain a lot of data transmitted from the view layer. Generally, multiple attributes of an object class are n. In many cases, there are many attributes of the object class, at this time, if the private variables of these attributes are defined one by one in the action in the previous method, and then the set and get methods are provided, this will make the entire action too bloated, this seriously hinders code readability and violates code reusability. In this case, we need to encapsulate these request parameters to improve code reusability, next, let's take a look at three methods to encapsulate request parameters:

1. encapsulate parameters using the object class

This method is the simplest way to encapsulate parameters. It is also commonly used, because in our struts application, we generally write the corresponding entity class according to the database information, so this is what we can use. Let's take a look at the specific operations below:

1. Create an object class user (including the username and password attributes). This is simple and we will not post the code.

2. create an action. Here we mainly look at the attributes of the data received by the action. We are not defining the private variables of these attributes one by one, we can directly define a private object corresponding to the object class. The Code is as follows:

package com.bzu.action;publicclass LoginAction extends ActionSupport {    private User user;    public User getUser() {        returnuser;    }    publicvoid setUser(User user) {        this.user = user;    }    public String execute(){    if(user.getUsername().equals("admin")&&user.getPassword().equals("123456"))            return"success";        return"fail";    }}

3. Define the form. here we need to note that the name attribute definition of the control in the form has certain requirements. when defining the name, we should define it:Object. AttributeFormat, sample code:

<S: Form Action = "loginaction"> <s: actionerror/> <s: textfield name = "user. username "> </S: textfield> <s: password name =" user. password "> </S: Password> <s: Submit value =" Submit "> </S: Submit> </S: Form>

4. Configure struts. xml. The configuration here is the same as that in normal cases and will not be repeated here.

So far, we have completed simple object class encapsulation Request Parameters. I believe everyone will feel very simple.

 

2.Model-driven encapsulation Request Parameters
Model-driven refers to the use of Javabean to encapsulate parameters for back-and-forth requests. This method reduces the pressure on actions. It is used to encapsulate parameters for back-and-forth requests, and also to protect the control logic, so that its structure is clear. This is the advantage of model-driven.

Next, let's take a look at the specific implementation of the model DRIVER:

The model-driven implementation is mainly reflected in the action

1. Create an object first, which is relatively simple and will not be written here.

2. Create an action class, inherit from actionsupport, and implement the modeldriven interface. This interface defines a GetModel () method for returning the defined model, and then calls the Set Method to assign values. Sample Code:

Publicclass loginaction3 extends actionsupport implementsmodeldriven <user> {private user = new user (); // remember to instantiate private loginservice = new loginserviceimpl (); // here is the business processing logic for calling logon @ override public user GetModel () {// todoauto-generated method stub return user;} Public String execute () {system. out. println (user. getUserName (); system. out. println (user. getPassword (); If (loginservice. islogin (user. getUserName (), user. getPassword () {return success;} return input ;}}



The source code of the COM. opensymphony. xwork2.modeldriven interface is described as follows:
Modeldriven actions provide a model object to bepushed onto the valuestack in additionto the action itself, allowing a formbeantype approach like struts
Translation: model-driven action. Put both the model object and action object in valuestack, And the formbean method like struts is allowed.
That is, to make an action model-driven, you must implement modeldriven
The previously inherited actionsupport class does not implement the modeldriven interface.

The execution process of the modeldrivenaction class is: first call the GetModel () method to obtain the user object, and then set the properties passed by the client to the properties of the user object one by one based on the JavaBean principle, after all the attributes are set, execute the execute () method. For model-driven systems, it is enough to understand this.

Extension: model-driven underlying Implementation Mechanism
The modeldriven interceptor in the defaultstack interceptor stack is used here.
It corresponds to the com. opensymphony. xwork2.interceptor. modeldriveninterceptor class. Its API description is as follows:
Public class modeldriveninterceptor extends actinterceptor
Watches For modeldriven actions and adds the action's model on to the valuestack.
Translate: Observe the model-driven action and put the model of this action [here refers to the user object] into the value stack.
Note: The modeldriveninterceptor must come before the bothstaticparametersinterceptor and parametersinterceptor if you want theparameters to be applied to the model.
Translation: If you want to apply the parameters submitted by the form to the model, the modeldriveninterceptor interceptor must be in front of the staticparametersinterceptor and parametersinterceptor interceptor.

The struts-default.xml has actually completed the job. You can view the three positions in the ultstack interceptor stack. For the model-driven method. in XML, you only need to specify the model-driven class. Other classes do not need to be manually modified.

3. Property-driven receiving Parameters

This method is not a parameter encapsulation method, but we usually use the attribute-driven method to receive parameters, because this method is convenient, concise, and easy to control. In the action, the property Driver provides a one-to-one attribute that corresponds to the form field, and then assigns values to each set. When the property-driven method is used, each attribute carries the Field Values of the form, run in the MVC process. Because this method is relatively simple, I will not repeat it here.


Is it property-driven or model-driven?

1) Unify the driver model used by actions in the system, that is, either property-driven or model-driven.

2) If the objects in the persistent layer in your DB correspond to the attributes in the form one by one, use model-driven. After all, the code looks much more neat.

3) if the attributes of a form are not one-to-one, the attribute driver should be used. Otherwise, your system must provide two beans and one corresponding data submitted by the form, another use and persistence layer.

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.