java的type转化class_第七章 (类型转换)Type Convertion
第七章 Type Convertion
為什么會(huì)有類型轉(zhuǎn)換?
HTTP協(xié)
議中傳遞的任何內(nèi)容都是String類型的,所以一旦我們?cè)诜?wù)器上需要一個(gè)非String類型的對(duì)象,例如:int或者Date,那么我們就需要在收到
HTTP請(qǐng)求的數(shù)據(jù)的時(shí)候,首先將String類型的數(shù)據(jù)變換為我們需要的對(duì)應(yīng)類型的數(shù)據(jù),之后再使用。這個(gè)過(guò)程就是類型轉(zhuǎn)換
類型轉(zhuǎn)換在Struts2中是透明的,即Struts2內(nèi)置了類型轉(zhuǎn)換機(jī)制。
轉(zhuǎn)換原理:
以一個(gè)例子來(lái)說(shuō)明如何使用Struts2內(nèi)置的類型轉(zhuǎn)換功能。加入我們希望用戶在畫面上輸入一個(gè)字符形式的坐標(biāo)點(diǎn),例如(33,2)而我們希望在程序中得到一個(gè)Point(33, 2)的類型與之對(duì)應(yīng)。
要想達(dá)到上面的功能我們需要一個(gè)名字位:ActionName-conversion.properties的文件,在文件中定義Action中的屬性和畫面字段之間的轉(zhuǎn)換關(guān)系。例如:
point = com.jpleasure.convertor.PointConverter
也
就是說(shuō)畫面一個(gè)叫做point的項(xiàng)目(input類型,name為point)提交到服務(wù)器上之后,在向Action中的point屬性賦值之前需要使用
PointConverter將字符串轉(zhuǎn)換為Point類,在Action中的point屬性向畫面顯示的時(shí)候需要使用PointConverter將
Point類轉(zhuǎn)換為字符串類型。
其中PointConverter需要實(shí)現(xiàn)ognl.TypeConverter接口。TypeConverter有兩個(gè)接口,一個(gè)負(fù)責(zé)將字符串轉(zhuǎn)變?yōu)閷?duì)象類型,另一個(gè)負(fù)責(zé)將對(duì)象類型轉(zhuǎn)換為字符串類型,分別對(duì)應(yīng)著內(nèi)容的提交和顯示。
有些時(shí)候我們希望所有的Point類在默認(rèn)的情況下使用PointConverter來(lái)轉(zhuǎn)換,這時(shí)候我們需要定義全局的Converter類。這可以在xwork-conversion.properties文件中定義,例如:
com.jpleasure.Point = com.jpleasure.convertor.PointConverter
在Struts2中提供了一個(gè)TypeConverter接口的默認(rèn)實(shí)現(xiàn):
org.apache.struts2.action.util.StrutsTypeConverter
這個(gè)類有兩個(gè)默認(rèn)的抽象轉(zhuǎn)換方法和performFallbackConversion,performFallbackConversion方法負(fù)責(zé)處理類型轉(zhuǎn)換出錯(cuò)的處理。
在
自定義TypeConverter的時(shí)候,可以實(shí)現(xiàn)TypeConverter接口,之后編寫TypeConverter的轉(zhuǎn)換方法,也可以從
StrutsTypeConverter繼承而來(lái),StrutsTypeConverter本身實(shí)現(xiàn)了TypeConverter接口,并且實(shí)現(xiàn)了基本的
轉(zhuǎn)換方法。
內(nèi)建的轉(zhuǎn)換:
Struts2內(nèi)建了對(duì)以下類型的轉(zhuǎn)換的支持:
String
boolean / Boolean
char / Character
int / Integer, float / Float, long / Long, double / Double
dates - 使用HTTP 請(qǐng)求對(duì)應(yīng)地域(Locale)的SHORT形式轉(zhuǎn)換字符串和日期類型。
arrays -每一個(gè)字符串內(nèi)容可以被轉(zhuǎn)換為不同的對(duì)象
collections - 轉(zhuǎn)換為Collection類型,默認(rèn)為ArrayList類型,其中包含String類型。
對(duì)于Array類型和Collection類型,需要對(duì)其中的每一個(gè)元素進(jìn)行單獨(dú)的轉(zhuǎn)換。
自定義TypeConverter:
使用如下的代碼自定義需要的TypeConverter
public class MyConverter extends StrutsTypeConverter {
public Object convertFromString(Map context, String[] values, Class toClass) {
.....
}
public String convertToString(Map context, Object o) {
.....
}
}
為了讓Struts2框架發(fā)現(xiàn)類型轉(zhuǎn)換的錯(cuò)誤,需要在出錯(cuò)的情況下在上述的兩個(gè)方法中拋出XWorkException或者TypeConversionException。
我們使用一個(gè)例子來(lái)展現(xiàn)如何實(shí)現(xiàn)TypeConvertor類型:
// Point 類
package com.jpleasure.conversion;
/**
* Created by IntelliJ IDEA.
* User: ma.zhao@dl.cn
* Date: 2007/09/04
* Time: 12:33:43
* To change this template use File | Settings | File Templates.
*/
public class Point {
private int x;
private int y;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = 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 String toString() {
StringBuffer sb = new StringBuffer("Point(");
sb.append(x).append(", ").append(y).append(")");
return sb.toString();
}
}
// PointConvertor 類
package com.jpleasure.conversion;
import org.apache.struts2.util.StrutsTypeConverter;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: ma.zhao@dl.cn
* Date: 2007/09/04
* Time: 12:34:18
* To change this template use File | Settings | File Templates.
*/
public class PointConvertor extends StrutsTypeConverter {
// 從字符串轉(zhuǎn)換為對(duì)象的方法。
public Object convertFromString(Map map, String[] strings, Class aClass) {
if (strings.length > 0) {
String pointStr = strings[0];
String[] pointStrArray = pointStr.split(",");
if (pointStrArray.length == 2) {
Point p = new Point();
p.setX(Integer.parseInt(pointStrArray[0]));
p.setY(Integer.parseInt(pointStrArray[1]));
return p;
} else {
return null;
}
} else {
return null;
}
}
// 從對(duì)象轉(zhuǎn)換為字符串的方法。
public String convertToString(Map map, Object o) {
if (o instanceof Point) {
return o.toString();
} else {
return "";
}
}
}
// 測(cè)試用PointAction類
package com.jpleasure.action;
import com.jpleasure.conversion.Point;
import com.opensymphony.xwork2.ActionSupport;
/**
* Created by IntelliJ IDEA.
* User: ma.zhao@dl.cn
* Date: 2007/09/04
* Time: 12:45:11
* To change this template use File | Settings | File Templates.
*/
public class PointAction extends ActionSupport {
private Point point;
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
public String execute() {
return SUCCESS;
}
}
// JSP文件
Created by IntelliJ IDEA.
User: ma.zhao@dl.cn
Date: 2007/09/04
Time: 12:47:40
To change this template use File | Settings | File Templates.
--%>
Point Page// PointAction配置文件類。
/p>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
/point/Point.jsp
/point/Point.jsp
復(fù)雜的類型轉(zhuǎn)換:
(1)處理Null值
有
些時(shí)候我們會(huì)被NullPointerException搞的焦頭爛額,為什么系統(tǒng)不能為我們定義了但是沒(méi)有初始化的對(duì)象建立一個(gè)空的Object的引用
呢?Struts2有這個(gè)功能,但是在默認(rèn)情況下Struts2關(guān)閉了這個(gè)功能,要想開(kāi)啟這個(gè)功能,需要在ParameterInterceptor開(kāi)始
處理參數(shù)之前在ValueStack中將一個(gè)值開(kāi)啟,這個(gè)值是:InstantiatingNullHandler.CREATE_NULL_OBJECTS。
在Java代碼中InstantiatingNullHandler.CREATE_NULL_OBJECTS的值是:xwork.NullHandler.createNullObjects
創(chuàng)建空值對(duì)象的規(guī)則為:
如果屬性聲明為Collection或List, 將返回一個(gè)ArrayList并賦值給空引用.
如果屬性聲明為Map, 將返回一個(gè)HashMap并賦值給空引用.
如果空值屬性是一個(gè)帶有無(wú)參構(gòu)造函數(shù)的簡(jiǎn)單Bean, 將使用ObjectFactory.buildBean(java.lang.Class, java.util.Map)方法創(chuàng)建一個(gè)實(shí)例.
(2)Collection和Map
簡(jiǎn)單List轉(zhuǎn)換
//JSP代碼
Created by IntelliJ IDEA.
User: mazhao
Date: 2007/09/04
Time: 12:47:40
To change this template use File | Settings | File Templates.
--%>
Point Page//Action代碼
package com.jpleasure.action;
import com.jpleasure.conversion.Point;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: ma.zhao@dl.cn
* Date: 2007/09/04
* Time: 12:45:11
* To change this template use File | Settings | File Templates.
*/
public class PointAction extends ActionSupport {
private Point point;
private List references;
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
public List getReferences() {
return references;
}
public void setReferences(List references) {
this.references = references;
}
public String execute() {
if(references == null) {
System.out.println("references is null");
} else {
System.out.println("references length is:" + references.size());
for(Object s: references) {
System.out.println("" + s);
}
}
return SUCCESS;
}
}
對(duì)象類型List轉(zhuǎn)換(key-value pair 方式)
// Person 類型
package org.apache.struts2.showcase.conversion;
import java.io.Serializable;
/**
*
*/
public class Person implements Serializable {
private String name;
private Integer age;
public void setName(String name) { this.name = name; }
public String getName() { return this.name; }
public void setAge(Integer age) { this.age = age; }
public Integer getAge() { return this.age; }
}
// PersionAction 類型
package org.apache.struts2.showcase.conversion;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
/**
*
*/
public class PersonAction extends ActionSupport {
private List persons;
public List getPersons() { return persons; }
public void setPersons(List persons) { this.persons = persons; }
public String input() throws Exception {
return SUCCESS;
}
public String submit() throws Exception {
return SUCCESS;
}
}
// PersonAction轉(zhuǎn)化配置文件PersonAction-conversion.properties
# PersonAction中persons屬性(List類型)中元素的類型
Element_persons=org.apache.struts2.showcase.conversion.Person
// JSP部分代碼
name="%{'persons['+#stat.index+'].name'}" />
name="%{'persons['+#stat.index+'].age'}" />
其中stat記錄了當(dāng)前循環(huán)的信息,其中stat.index表示當(dāng)前循環(huán)的下標(biāo)。
所以上述代碼會(huì)生成如下的代碼:
name="persons[0].name" />
name="persons[0].age" />
name="persons[1].name" />
name="persons[1].age" />
name="persons[2].name" />
name="persons[2].age" />
對(duì)象類型List轉(zhuǎn)換(value 方式)
// Address 類型
package org.apache.struts2.showcase.conversion;
/**
* @version $Date: 2006-11-23 12:31:52 -0500 (Thu, 23 Nov 2006) $ $Id: Address.java 478625 2006-11-23 17:31:52Z wsmoak $
*/
public class Address {
private String id;
private String address;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
}
// AddressAction 類型
package org.apache.struts2.showcase.conversion;
import java.util.LinkedHashSet;
import java.util.Set;
import com.opensymphony.xwork2.ActionSupport;
/**
* @version $Date: 2006-11-23 12:31:52 -0500 (Thu, 23 Nov 2006) $ $Id: AddressAction.java 478625 2006-11-23 17:31:52Z wsmoak $
*/
public class AddressAction extends ActionSupport {
private Set addresses = new LinkedHashSet();
public Set getAddresses() { return addresses; }
public void setAddresses(Set addresses) { this.addresses = addresses; }
public String input() throws Exception {
return SUCCESS;
}
public String submit() throws Exception {
System.out.println(addresses);
return SUCCESS;
}
}
//AddressAction轉(zhuǎn)換配置文件AddressAction-conversion.properties
KeyProperty_addresses=id
Element_addresses=org.apache.struts2.showcase.conversion.Address
CreateIfNull_addresses=true
// JSP代碼
name="%{'addresses(\\'id'+#stat.index+'\\').address'}" />
上述代碼會(huì)轉(zhuǎn)換為:
name="addresses('id0')" />
name="addresses('id1')" />
name="addresses('id2')" />??
注意兩個(gè)地方:
第一,沒(méi)有向服務(wù)器提交Address的id屬性,那么Address的id屬性是什么呢?
KeyProperty_addresses=id表示向服務(wù)器提交的內(nèi)容的key部分("id0”, "id1”, "id2”)會(huì)被認(rèn)定為Addredd的id。
第二,CreateIfNull_addresses=true表示及時(shí)客戶端沒(méi)有向服務(wù)器提交任何Address內(nèi)容,服務(wù)器也會(huì)為AddressAction的addresses 建立一個(gè)長(zhǎng)度為0的Set。
相關(guān)的一些經(jīng)驗(yàn)
開(kāi)發(fā)的過(guò)程中不要一味的使用String類型,使用String類型無(wú)論在處理的速度還是內(nèi)
存的使用上都不是最好的方式。一般情況下,Java的模型類(JavaBean,
Action等都可以視為Java模型類,因?yàn)槠渲斜硎玖四P偷男畔?,一般情況下需要和數(shù)據(jù)庫(kù)中的類型一致。這樣才能保證最好的性能。
那么像java.util.Date,Integer等類型需要表示到JSP頁(yè)面上的時(shí)候還是需要表示為String類型的,但是Struts2都已經(jīng)幫助實(shí)現(xiàn)了,所以請(qǐng)使用具體的類型吧,不要總是使用String類型。
ExtJS教程-Hibernate教程-Struts2 教程-Lucene教程
總結(jié)
以上是生活随笔為你收集整理的java的type转化class_第七章 (类型转换)Type Convertion的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c语言程序前言,C语言 程序代码编写规范
- 下一篇: 计算机英语四六级对调剂有影响吗,你知道四