In-depth analysis of JavaWeb Item45 -- Struts2 encapsulation Request Parameters and type conversion

Source: Internet
Author: User
Tags ocaml

In-depth analysis of JavaWeb Item45 -- Struts2 encapsulation Request Parameters and type conversion

As an MVC Framework, it must be responsible for parsing HTTP Request Parameters and encapsulating them into Model objects. Struts2 provides a very powerful type conversion mechanism for requesting data to encapsulate the model object.

1. Struts2 provides three data encapsulation methods: Action itself acts as a model object and is encapsulated by a member setter.

Create an independent model object. The page is encapsulated by ognl expressions.

Use the ModelDriven interface to encapsulate the request data

1. Method 1: Assign the initial value to the member variables in the dimensions class.

In the configuration file struts. xml


                      
   
    /result.jsp
           
  

Compile result. jsp

  
${name}

Write the implementation class PersonAction and override the excute () method.

Package com. itheima. actions; import com. opensymphony. xwork2.ActionSupport; public class PersonAction extends ActionSupport {private String name = "Liu xiaochen"; private String password; private int age; public String getName () {return name ;} public void setName (String name) {System. out. println ("setName method called"); this. name = name;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String execute () throws Exception {System. out. println (name + ":" + password + ":" + age); return super.exe cute ();}}

Running result: Liu xiaochen

In this way, when a member variable of the class is assigned, the parameter value of the category class can also be injected into the configuration file (static parameter setting), and the Action itself serves as the model object, encapsulated by a member setter (an interceptor named params)

Reconfigure struts. xml as follows:

  
                       
   Wang weixing
   
    
/Result. jsp
               
  

Running result: Wang weixing

Is actually done by an interceptor called staticParams, you can view the struts-default.xml configuration file, if the staticParams interceptor is deleted, then do not get the desired results

In addition, dynamic parameter injection also uses the model class as the model object.

Compile result. jsp

 

The configuration file and Action Implementation class remain unchanged. Note the following:The name, password, and age of the input field must be the same as the write attribute name of the category.

Running result: name input result in the form.

Dynamic Parameter injection is also implemented by an interceptor:Params

2. Method 2: Separate the callback class from the model (we use form request parameters as an example)

Write the configuration file struts. xml

Compile the required class StudentAction

Package com. itheima. actions; import com. itheima. domain. student; import com. opensymphony. xwork2.ActionSupport; public class StudentAction extends ActionSupport {private Student student = new Student (); public Student getStudent () {System. out. println ("getStudent method called"); return student;} public void setStudent (Student student) {System. out. println ("The setStudent method is called"); this. student = student;} public String execute () throws Exception {System. out. println (student); return NONE ;}}

Compile model class Student. java

package com.itheima.domain;import java.io.Serializable;public class Student implements Serializable {    private String name;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return "Student [name=" + name + ", age=" + age + "]";    }}

Write the access page addStudent. jsp

  

In this way, Student and StudentAction are separated. On the page, student. name and student. age can be used to encapsulate request parameters.

The main principles are as follows:

The framework creates a Student instance. By calling setStudent (Student s), it passes the object framework and then calls the getStudent () of StudentAction. The method is followed by the newly created object, call the setName and setAge methods of the student instance to set the value. 3. Method 3: model-driven (interview)(Related to the ValueStack value stack)

Compile the struts. xml configuration file

Compile the meraction category

Package com. itheima. actions; import com. itheima. domain. customer; import com. opensymphony. xwork2.ActionSupport; import com. opensymphony. xwork2.ModelDriven; // model-driven: public class CustomerAction extends ActionSupport implements ModelDriven
  
   
{Private Customer customer = new Customer (); // here, a new () object class must be generated. Public Customer getCustomer () {return customer;} public void setCustomer (Customer customer) {this. customer = customer ;}@ Override public String execute () throws Exception {System. out. println (customer); return NONE;} public Customer getModel () {return customer ;}}
  

Write object class Customer. java

package com.itheima.domain;import java.io.Serializable;public class Customer implements Serializable {    private String name;    private String city;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }    @Override    public String toString() {        return "Customer [name=" + name + ", city=" + city + "]";    }}

Write the addCustomer. jsp page

  

Here, you can directly write name and city to encapsulate the request parameters without the need for customer. name and customer. city.

Note: The model driver is actually implemented by an interceptor.ModelDriven interceptor. Push the object returned by the getModel method into an object calledValueStackStack top. Based on the name attribute of the form, the struts Framework calls the setter method of the corresponding stack top object to encapsulate the request parameters. You can refer to the source code:
Note thatIt must be new!Otherwise, the Framework calls the getCustomer () method of CustomerAction and returns null.

2. encapsulate data into the set type

Struts2 also allows objects in the Collection to be filled, which is common when batch data needs to be quickly entered.

Type conversion and Collection

Use data type conversion with Map

Instance:

Compile and configure struts. xml

Compile the collect action class

Package com. itheima. actions; import java. util. arrays; import java. util. collection; import java. util. map; import com. itheima. domain. employee; import com. opensymphony. xwork2.ActionSupport; public class CollectionAction extends ActionSupport {private String [] Hoby; // array private Collection
   
    
Employees; // set private Map
    
     
Emps; // map public String [] getholobby () {return holobby;} public void setholobby (String [] holobby) {this. holobby = holobby;} public Collection
     
      
GetEmployees () {return employees;} public void setEmployees (Collection
      
       
Employees) {this. employees = employees;} public Map
       
         GetEmps () {return emps;} public void setEmps (Map
        
          Emps) {this. emps = emps;} public String execute () throws Exception {// System. out. println (Arrays. asList (holobby); // System. out. println (employees); if (emps! = Null) {for (Map. Entry
         
           Me: emps. entrySet () {System. out. println (me. getKey () + ":" + me. getValue () ;}} return NONE ;}}
         
        
       
      
     
    
   

Compile an object class Employee

package com.itheima.domain;import java.io.Serializable;public class Employee implements Serializable {    private String name;    private float salary;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public float getSalary() {        return salary;    }    public void setSalary(float salary) {        this.salary = salary;    }    @Override    public String toString() {        return "Employee [name=" + name + ", salary=" + salary + "]";    }}

Compile collectionDemo. jsp

  
Add employee information in batches 
Add content to Map3. type conversion 

For most common types, developers do not need to create their own converters at all. Struts2 has built-in multiple common data types to automatically convert 8 basic types.
-Boolean and Boolean
-Char and Character
-Int and Integer
-Long and Long
-Float and Float
-Double and Double
-Date can receive strings in the yyyy-MM-dd format, java. util. Date <---> String (China: Struts2 automatically converts strings in the local format of yyyy-MM-dd by default)
-An array can convert multiple parameters with the same name to an array.
-The set supports saving data to the List or Map set.

Conclusion: there is basically no need to write any type converter when using Struts2. The built-in functions are sufficient.

However, because the data transmitted from the user interface is String: String --> other types, when some requirements are display or data ECHO: Other types --> String, we need to convert the custom type.

Let's take a look at the source code. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwPjxpbWcgYWx0PQ = "here write picture description" src = "http://www.bkjia.com/uploads/allimg/160110/042R5A51-7.png" title = "\"/>

From the source code, we can see that the inheritanceorg.apache.struts2.util.StrutsTypeConverter(Simple and Convenient)

1. Custom type converter

String ------> java. util. Date MM/dd/yyyy --> convertible
Java. util. Date ---> String MM/dd/yyyy

Steps:

1. Compile a class for direct or indirect implementation:
Com. opensymphony. xwork2.conversion. TypeConverter interface.
You can also choose inheritance:
Com. opensymphony. xwork2.conversion. impl. DefaultTypeConverter

We choose to inheritorg.apache.struts2.util.StrutsTypeConverterAnd overwrite the following method:
Public Object convertValue (Object value, Class toType)

Assume that there is a time parameter createtime in the response class HelloWorldAction.

import java.util.Date;public class HelloWorldAction {    private Date createtime;    public Date getCreatetime() {        return createtime;    }    public void setCreatetime(Date createtime) {        this.createtime = createtime;    }}

Customize our converter MyDateConvertor, covering the convertFromString () and convertToString () methods.

Package com. itheima. convertor; import java. text. dateFormat; import java. text. parseException; import java. text. simpleDateFormat; import java. util. date; import java. util. map; import org. apache. struts2.util. strutsTypeConverter; // Date converter:/** String: 12/31/2001 ----> Date * Date ----------> String: 12/31/2001 */public class MyDateConvertor extends StrutsTypeConverter {private DateFormat df = new SimpleDateFormat ("MM/dd/yyyy"); // convert from string to date public Object convertFromString (Map context, string [] values, Class toClass) {if (toClass = Date. class) {String value = values [0]; // obtain the user input parameter value 12/31/2001 try {return df. parse (value);} catch (ParseException e) {e. printStackTrace () ;}return null;} // convert a Date to a public String convertToString (Map context, Object o) {if (o instanceof Date) {Date d = (Date) o; return df. format (d) ;}return null ;}}

2. Register a type converter

Local Converter: Special service for a certain category of services)

Place the ActionClassName-conversion.properties file under the package where the Action class is located, ActionClassName is the class name of the Action, followed by-conversion. properties is a fixed syntax, for this example, the file name should beHelloWorldAction-conversion.properties. The content in the properties file is:

Attribute name = full Class Name of the type converter

For this example, the content in the HelloWorldAction-conversion.properties file is:

Createtime = cn. itcast. conversion. DateConverter

Global Converter: For all the ingress class services
Create a config file with a fixed name under the WEB-INF \ classes directory (under src:Xwork-conversion.properties

For this example, the content in the xwork-conversion.properties file is:
Java. util. Date = cn. itcast. conversion. DateConverter

3. Page redirection and error message prompts when conversion fails
Struts2 provides an interceptor named conversionError to view struts-default.xml


          

If the Struts2 type converter encounters an error during type conversion, the interceptor is responsible for encapsulating the corresponding error into a form field error (FieldErrorAnd put the error information in ActionContext.
To use error handling in type conversion, user-defined actions must inherit ActionSupport

In a custom type converter, an exception must be thrown and cannot be captured. conversionError will handle the exception and be transferred to the logic view named input.
In the Action package, create ActionName. properties and configure the prompt information in the local resource file:Invalid. fieldvalue. attribute name = error message
In the jsp page corresponding to the input logic view Output type conversion information

A. configure a result view with name = "input", which generally points to the page of user input data.

B. Use the struts2 label in the sp to display field-related errors (subsequent international discussion)

<%@ taglib="" uri="/struts-tags" prefix="s">     
           
<% @ Taglib = "" uri = "/struts-tags" prefix = "s">

C. If the configuration prompt is in Chinese
In the package where the consumer class is located, create a configuration file named "consumer class name. properties ".

 

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.