Obtain Request Parameters in Struts2
In Strucs, Action is responsible for processing Request Parameters. How does Action be implemented? This blog post will give you a brief introduction. In struts, there are two methods to obtain request parameters:
1. Attribute-Driven Mode
Method 1: use the property driver to directly use the Action as the Model. However, if this is not done well, the parameter cannot be uploaded to the Service layer for further processing.
Package cn. tgb. action; // Method 1: use Attribute-driven Action as Modelpublic class Action01 {private String name; private String passwrod; public String getName () {return name ;} public void setName (String name) {this. name = name;} public String getPassword () {return passwrod;} public void setPassword (String password) {this. passwrod = password;} public String login () {System. out. println (name + "" + passwrod); return null ;}}
Method 2: Add a reference to the Model in the Action. The advantage of this is that the request parameters are directly encapsulated in the javaBean and do not need to be copied through action. The disadvantage is that some ognl expressions are required on the page.
Package cn. tgb. action; import cn. tgb. model. user; // Method 2: Use the property driver to add the reference public class Action02 {private User user; public User getUser () {return user;} to the Model in Action ;} public void setUser (User user) {this. user = user;} public String login () {System. out. println (user. getName () + "" + user. getPassword (); return null ;}}
2. model-driven Mode
To use a model driver, you must make the Action implement the ModelDriven interface. This method needs to instantiate the model object in the Action, and then rewrite the getModel () method in the ModelDriven interface to return this object.
Package cn. tgb. action; import cn. tgb. model. user; import com. opensymphony. xwork2.ActionSupport; import com. opensymphony. xwork2.ModelDriven; // method 3: // GET Request Parameters -- use the model to drive public class Action03 extends ActionSupport implements ModelDriven
{Private User user = new User (); @ Overridepublic User getModel () {return user;} public String login () {System. out. println (user. getName () + "" + user. getPassword (); return null ;}}