struts2自定义类型转换器

        ognl可以把我们转换基本类型的数据,不过如果是我们自定义的类类型,框架就没有办法帮助我们填充数据了,这是我们就需要自定义类型转换器。
package com.util;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.po.Point;

public class ConverterPoint extends StrutsTypeConverter{

	@Override
	public Object convertFromString(Map map, String[] parameter, Class classname) {
	    
		//用户输入的信息在String[] parameter数组中,下标为0的位置
		String pointmessage = parameter[0];
		String [] message = pointmessage.split(",");
		
		String x = message[0];
		String y = message[1];
		
		int  xx = Integer.parseInt(x);
		int  yy = Integer.parseInt(y);
		
		Point point = new Point();
		point.setX(xx);
		point.setY(yy);
		
		return point;
	}

	@Override
	public String convertToString(Map map, Object object) {
		
	    //和toString的道理差不多
		StringBuffer  message =new StringBuffer("横坐标为:");
		Point point = (Point)object;
		message.append(point.getX()+"  纵坐标为:");
		message.append(point.getY());
		return   message.toString();
	}
   
}


 

    页面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix= "s" uri = "/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <s:form method="post" action="Converter.action">
       <s:textfield name="point" label="坐标信息   x,y"></s:textfield>
       <s:submit value="提交"></s:submit>
    </s:form>
  </body>
</html>


 

  action

package com.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.po.Point;

public class Converter implements Action {

	private Point point ;
	
	public String execute() throws Exception {
		
		System.out.println("x="+point.getX());
		System.out.println("y="+point.getY());
		
		HttpServletRequest request = ServletActionContext.getRequest();  
		request.setAttribute("point", point);
		
	    return "success";
	}
	
	public Point getPoint() {
		return point;
	}
	public void setPoint(Point point) {
		this.point = point;
	}
	
	

}


 

     告诉框架如何找到类型转换规则

新建Converter-conversion.properties文件,文件名的格式为 action-conversion.properties,本例子中action名为Converter,并且写上

  point=com.util.ConverterPoint

 

key 是 我们需要 填充的属性  value 是 转换类

你可能感兴趣的:(struts2自定义类型转换器)