当前位置: 首页 > 图文教程 > Java技术 > Web框架 > struts2(五)
在我已往的Struts 1.x项目经验中,有个问题不时的出现——在创建FormBean时,对于某个属性到底应该用String还是其它类型?
package tutorial;
import java.util.Locale;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
public class HelloWorld extends ActionSupport {
private String msg;
private Locale loc = Locale.US;
public String getMsg() {
return msg;
}
public Locale getLoc() {
return loc;
}
public void setLoc(Locale loc) {
this .loc = loc;
}
@Override
public String execute() {
// LocalizedTextUtil是Struts 2.0中国际化的工具类,<s:text>标志就是通过调用它实现国际化的
msg = LocalizedTextUtil.findDefaultText( " HelloWorld " , loc);
return SUCCESS;
}
}
package tutorial;
import java.util.Locale;
import java.util.Map;
public class LocaleConverter extends ognl.DefaultTypeConverter {
@Override
public Object convertValue(Map context, Object value, Class toType) {
if (toType == Locale. class ) {
String locale = ((String[]) value)[ 0 ];
return new Locale(locale.substring( 0 , 2 ), locale.substring( 3 ));
} else if (toType == String. class ) {
Locale locale = (Locale) value;
return locale.toString();
}
return null ;
}
} 

实现转换器,我们需要通过配置告诉Struts 2.0。我们可以通过以下两种方法做到这点:
![]() | 在继承DefaultTypeConverter时,如果是要将value转换成其它非字符串类型时,要记住value是String[]类型,而不是String类型。它是通过request.getParameterValues(String arg)来获得的,所以不要试图将其强行转换为String类型。 |
对于已有的转换器,大家不必再去重新发明轮子。Struts在遇到这些类型时,会自动去调用相应的转换器。
package tutorial;
import java.util.Date;
publicclass Product {
private String name;
privatedouble price;
private Date dateOfProduction;
public Date getDateOfProduction() {
return dateOfProduction;
}
publicvoid setDateOfProduction(Date dateOfProduction) {
this.dateOfProduction = dateOfProduction;
}
public String getName() {
return name;
}
publicvoid setName(String name) {
this.name = name;
}
publicdouble getPrice() {
return price;
}
publicvoid setPrice(double price) {
this.price = price;
}
}
package tutorial;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
publicclass ProductConfirm extends ActionSupport {
public List<Product> products;
public List<Product> getProducts() {
return products;
}
publicvoid setProducts(List<Product> products) {
this.products = products;
}
@Override
public String execute() {
for(Product p : products) {
System.out.println(p.getName() + " | "+ p.getPrice() +" | " + p.getDateOfProduction());
}
return SUCCESS;
}
}



评论 (0) All