码迷,mamicode.com
首页 > 其他好文 > 详细

struts2类型转换器

时间:2016-06-14 17:43:10      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

类型转换器分为全局类型转换器和局部类型转换器。全局类型转换针对所有Action都起作用,而局部类型转换器针对某个Action

一、全局类型转换器。将字符串x,y转换成Point

Login.jsp页面

<s:form method="post" action="test">
        <s:textfield name="username" label="账号"></s:textfield>
        <s:password name="password" label="密码"></s:password>
        <s:textfield name="point" label="坐标"></s:textfield>
        <s:submit></s:submit>
    </s:form>

 

定义实体类

技术分享
package models;

public class Point {

    private int x;
    private int y;
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
    
    public Point() {
    }
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
}
Point.java
技术分享
package models;

public class User {

    private String username;
    private String password;
    private Point point;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Point getPoint() {
        return point;
    }
    public void setPoint(Point point) {
        this.point = point;
    }
    
}
User.java

 

定义Action类

技术分享
package action;

import com.opensymphony.xwork2.ModelDriven;

import models.Point;
import models.User;

public class Test implements ModelDriven<User> {

    private User user=new User();
    public String execute(){
        System.out.println(user.getPoint());
        return "success";    
    }
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }
}
Test.java

 

定义类型转换器

技术分享
package coverter;

import java.util.Map;

import models.Point;

import org.apache.struts2.util.StrutsTypeConverter;

public class PointConverter extends StrutsTypeConverter{

    @Override
    public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
        Point point=null;
        if(arg1.length>0){
            point=new Point();
            String[] cods=arg1[0].split(",");
            point.setX(Integer.parseInt(cods[0]));
            point.setY(Integer.parseInt(cods[1]));
        }
        return point;
    }

    @Override
    public String convertToString(Map arg0, Object arg1) {
        Point point=(Point)arg1;
        return point.getX()+","+point.getY();
    }

}
PointConverter.java

 

在src下新建一个xwork-conversion.properties文件,内容如下:

models.Point=coverter.PointConverter

前面是需要类型转换的类,后面是转换器

struts2类型转换器

标签:

原文地址:http://www.cnblogs.com/caoyc/p/5584642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!