天天看點

自定義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 [email protected](name="documentId"):向新加入的這個表中添加一個字段名稱為:documentId,這個值将作為新添加的這個表的主鍵
			joinColumns [email protected](name="documentId")
	)
//因為這個屬性是Map類型的key是String類型value是DocumentProperty類型,指定這個注解是将Map的key值作為新添加的這個表中的一個字段,并且是主鍵。
	@MapKey([email protected](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){}           

這兩個方法什麼都不用做,添加上之後就不會報錯了,檔案上傳成功!