Struts2 learning (nine) type converter

Struts2 learning (nine) type converter

Background and significance of type converters

Type conversion is an inevitable part of daily web development,
because the data submitted from the form to the backend uses String as the default data type, and when we encapsulate it into an object in the backend, there may be multiple types of forms.

The conversion of data types according to the previous method is realized by the type conversion of java. The specific steps are:

Int age = Integer.valueOf(request.getParameter("age")); 
Double money = Double .valueOf(request.getParameter("money"))

Struts2 data type conversion

In Struts2, automatic conversion and encapsulation between basic data types are provided for us, and the conversion between String and basic data types is automatically completed by the Struts2 framework:

  • String and boolean complete the conversion between strings and booleans
  • String and char complete the conversion between strings and characters
  • String and int , Integer complete the conversion between strings and integers
  • String and Long complete the conversion between strings and long integer values
  • String and Double complete the conversion of strings to double-precision floating-point values
  • String and Float complete the conversion between strings and single-precision floating point
  • String and array In the default case, the elements of the array are strings. If the user defines a type converter, it can also be other composite data types.
  • String and Date complete the conversion between string and date types (the format must be xxxx-xx-xx)

But the conversion of some custom data types will use the methods provided by Struts2 for us.

struts2 provides us with two different type converters: local type converters and global type converters.

local type converter

The so-called local type converter is: only acts on one action class!

demo

Let's write a Date type type converter. The format of the form input is: 20120101
Before writing the type converter, first write the corresponding JSP interface

<%@ page contentType="text/html;charset=UTF-8" language="java" %> 
<html> 
<head> 
    <title>Title</title> 
</head> 
<body> 
<form method="post" action="ch08TestAction1.action"> 
    请输入日期(示例:20120101):<input type="text" name="position"> 
    <input type="submit" value="提交"> 
</form> 
</body> 
</html> 

Step 1: Create a custom type converter class, inherit the DefaultTypeConverter class, and override the convertValue method in it

package cn.lovepi.chapter08.action; 
import ognl.DefaultTypeConverter; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.Map; 
/** 
* Date类型转换器-局部类型转换器(只能作用于一个action类) 
* --------------------------------- 
* 我们实现类型转换器有两种方法: 
* 1.继承ognl的DefaultTypeConverter类或者实现TypeConverter接口。 
* 2.基于Struts2库,实际上struts2库也是基于ognl的二次封装 
* 只是简化了一定的操作,也是继承DefaultTypeConverter类,只是包名不同而已 
* 
* 两种方式的区别: 
* ognl只重写一个方法,实现双向的转换 
* struts2则重写两个方法, 
*      一个是从字符串转换为某种类型,convertFromString 
*      另一个是从某种类型转换为字符串,convertToString 
* ---------------------------------------------------- 
* 最后还需将转换类和action类关联在一起,即在action类同包下创建关联文件。 
*/ 
public class DateConver extends DefaultTypeConverter{ 
    /** 
     * 类型转换方法 
     * 此方法根据toType来判断是否执行 
     * @param context 类型转换的上下文 
     * @param value 前台传递过来的数据 
     * @param toType 转换后的目标类型 
     * @return 
     */ 
    @Override 
    public Object convertValue(Map context, Object value, Class toType) { 
        //struts2基于更全面的考虑,将参数以数组的方式接收 
        // 防止用户提交的要转换的数据是多选 
        String[] params= (String[]) value; 
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd"); 
        Date da=null; 
        try { 
            da=sdf.parse(params[0]); 
        } catch (ParseException e) { 
            e.printStackTrace(); 
        } 
        return da; 
    } 
} 

Step 2 : Create a local converter configuration file

Name format: ActionName-conversion.properties
File location: under the same package as action
Content : property name = custom converter path
Example (times = com.jike.coverter.DateTypeConverter)

First write the Action you need to use: TestAction

package cn.lovepi.chapter08.action; 
import com.opensymphony.xwork2.ActionSupport; 
import java.util.Date; 
/** 
* 类型转换器-测试Action 
* 首先没有使用转换器的时候讲解错误 
* 基本数据类型可以被struts2自动转换,如int的属性,表单数据可直接转为uint 
* 但Date类型不是基本数据类型,得自己手动的写一个转换的方法 
*/ 
public class TestAction extends ActionSupport{ 
    private Date times; 
    @Override 
    public String execute() throws Exception { 
        System.out.println("时间:"+times.toString()); 
        return SUCCESS; 
    } 
    public Date getTimes() { 
        return times; 
    } 
    public void setTimes(Date times) { 
        this.times = times; 
    } 
} 

Configure it in struts.xml

<package name="chapter08" extends="struts-default"> 
        <action name="ch08TestAction" class="cn.lovepi.chapter08.action.TestAction"> 
            <result name="success">/chapter08/index.jsp</result> 
        </action> 
</package> 

Write a configuration file: TestAction-conversion.properties

times=cn.lovepi.chapter08.conver.DateConver 

Where: on the left is the name of the property, on the right is the full path name of the converter

global type converter

The so-called local type converter is: acting on all action classes!

Example Demonstration: Coordinate Type Conversion

Let's write a type converter for coordinates, the format of the form input is: 12.8, 13.6

Before writing the type converter, first write the corresponding JSP interface

<%@ page contentType="text/html;charset=UTF-8" language="java" %> 
<html> 
<head> 
    <title>Title</title> 
</head> 
<body> 
<form method="post" action="ch08TestAction1.action"> 
    请输入坐标值(示例:12.8,13.6):<input type="text" name="position"> 
    <input type="submit" value="提交"> 
</form> 
</body> 
</html> 

The corresponding conversion result display interface:

<%@ page contentType="text/html;charset=UTF-8" language="java" %> 
<%@ taglib prefix="s" uri="/struts-tags" %> 
<html> 
<head> 
    <title>Title</title> 
</head> 
<body> 
<s:property value="position"/> 
</body> 
</html> 

And the bean object used in the demo:

package cn.lovepi.chapter08.bean; 
/** 
* 坐标实体类 
*/ 
public class MyPosition { 
    private float x; 
    private float y; 
    public float getX() { 
        return x; 
    } 
    public void setX(float x) { 
        this.x = x; 
    } 
    public float getY() { 
        return y; 
    } 
    public void setY(float y) { 
        this.y = y; 
    } 
} 

Step 1: Create a custom type converter class, inherit the DefaultTypeConverter class, and override the convertValue method in it

package cn.lovepi.chapter08.conver; 
import cn.lovepi.chapter08.bean.MyPosition; 
import ognl.DefaultTypeConverter; 
import java.util.Map; 
/**  
* 全局转换器 
*/ 
public class PositionConver extends DefaultTypeConverter{ 
    @Override 
    public Object convertValue(Map context, Object value, Class toType) { 
        MyPosition position; 
        //假如是从前台传到后台 
        if (toType== MyPosition.class){ 
            String[] params= (String[]) value; 
            String[] xy=params[0].split(","); 
            position=new MyPosition(); 
            position.setX(Float.valueOf(xy[0])); 
            position.setY(Float.valueOf(xy[1])); 
            return position; 
        } 
        //从后台传到前台,在界面上使用<s:property来显示 
        if (toType==String.class){ 
            position= (MyPosition) value; 
            return "坐标:("+position.getX()+","+position.getY()+")"; 
        } 
        return null; 
    } 
} 

Step 2 : Create a global converter configuration file
Name format: xwork-conversion.properties
file location: project root directory, under src
Content : type name = custom converter path

例(java.util.Date =com.jike.coverter.DateTypeConverter)

First create the corresponding Action, TestAction1

package cn.lovepi.chapter08.action; 
import cn.lovepi.chapter08.bean.MyPosition; 
import com.opensymphony.xwork2.ActionSupport; 
import org.apache.struts2.ServletActionContext; 
/** 
* 全局转换器Action 
*/ 
public class TestAction1 extends ActionSupport{ 
    MyPosition position; 
    @Override 
    public String execute() throws Exception { 
        System.out.println("X坐标:"+position.getX()+",Y坐标:"+position.getY()); 
        ServletActionContext.getRequest().setAttribute("position",position); 
        return SUCCESS; 
    } 
    public MyPosition getPosition() { 
        return position; 
    } 
    public void setPosition(MyPosition position) { 
        this.position = position; 
    } 
} 

Configure it in struts.xml

<package name="chapter08" extends="struts-default"> 
        <action name="ch08TestAction1" class="cn.lovepi.chapter08.action.TestAction1"> 
            <result name="success">/chapter08/po.jsp</result> 
        </action> 
</package> 

Next, create a global converter configuration file xwork-conversion.properties in the src directory

cn.lovepi.chapter08.bean.MyPosition=cn.lovepi.chapter08.conver.PositionConver 

Where: the left is the full path name of the type to be converted, and the right is the full path name of the required converter

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325692599&siteId=291194637