`

自定义struts转换器实现向Map中存放对象类型数据

阅读更多
1、Document类:重点关注properties属性的映射及如何从页面向这种Map类型中存放数据
@Entity
@Table(name="t_document")
public class Document {
	@Id
	@GeneratedValue
	private int id;
	private String title;
	@Type(type="binary")
	@Column(length=99999999)
	private byte[] annex; //附件
	private long processInstanceId;
	private String description;
	private String status; //状态
	private Date createTime;
	@ManyToOne
	private WorkFlow workFlow;
	
	@ManyToOne
	private User creator; //公文创建者
	
//此属性存放的是集合类型 
	@CollectionOfElements
//为存放这个集合类型添加一张表 name:指定表的名称
	@JoinTable(name="t_documentproperties",
//joinColumns =@JoinColumn(name="documentId"):向新加入的这个表中添加一个字段名称为:documentId,这个值将作为新添加的这个表的主键
			joinColumns =@JoinColumn(name="documentId")
	)
//因为这个属性是Map类型的key是String类型value是DocumentProperty类型,指定这个注解是将Map的key值作为新添加的这个表中的一个字段,并且是主键。
	@MapKey(columns=@Column(name="propertyName"))
	private Map<String, DocumentProperty> properties;


2、DocumentProperty类
@Embeddable
public class DocumentProperty {
	
	private String java_lang_String;
	
	private Integer java_lang_Integer;
	
	@Type(type="binary")
	@Column(length=99999999)
	private byte[] java_io_File;
	
	private Long java_lang_Long;
	
	private Date java_util_Date;
	
	@Column(nullable=false)
	private String propertyType;
}


3、Action中的写法:在Action中不用做特别的定义因为Map类型的properties是Document的一个属性
@Component
@Scope("prototype")
public class DocumentAction extends BaseAction {
	
	private Document doc = new Document();
}


4、页面应该怎么写?

在jsp文件中我们向Map中提交数据对于一些基本的数据类型strtus2都自己能做转换
例如:<input type="xxx" name="properties['username'].java_lang_String" value="xxx" />意为:
'username'是此Map的key值,而java_lang_String 是DocumentProperty对象中的一个属性,那么这个输入域
的value值就赋值给这个字段,我们在DocumentProperty中定义的java_io_File是byte[]类型的,struts2默认
无法将java.io.File转换为byte[]类型,所以我们需要自己写一个转换器。

5、定义自己的转化器将java.io.File类型转化为byte[]类型
//继承strust2给我们提供的DefaultTypeConverter类
public class ByteArrayConverter extends DefaultTypeConverter {

	@Override
	public Object convertValue(Map<String, Object> context, Object value,
			Class toType) {
		File[] files = (File[])value;
		if(files == null || files.length == 0) {
			return null;
		}
		
		try {
			return FileUtils.readFileToByteArray(files[0]);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}


写完上面这个转换器之后,我们还要添加一个配置文件,你要对哪个类中的这个属性进行转换就配置文件就以哪个类名开头然后-conversion.properties。我们这个例子是对DocumentProperty这个类中的java.io.File这个类型进行转换,所以我们配置文件的名称为DocumentProperty-conversion.properties。文件内容:
java_io_File=com.bjsxt.oa.model.ByteArrayConverter

这样当他对java_io_File这个属性赋值的时候就会来找到这个配置文件,然后交给com.bjsxt.oa.model.ByteArrayConverter这个类来处理,在这个类中我们将java.io.File类型转为byte[]类型。这个配置文件默认要放到与要转换的类同一个目录下面struts2才能找得到。

这个地方其实有struts2一个bug我们定义了转换器,但是后台还是会报错文件无法上传,我们还要在DocumentProperty类中增加两个方法才可以:
public void setJava_io_FileFileName(String s){}
	public void setJava_io_FileContentType(String s){}

这两个方法什么都不用做,添加上之后就不会报错了,文件上传成功!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics