读书人

struts2入门(三)

发布时间: 2013-03-06 16:20:31 作者: rapoo

struts2入门(3)
指定需要Struts 2处理的请求后缀前面我们都是默认使用.action后缀访问Action。其实默认后缀是可以通过常量”struts.action.extension“进行修改的,例如:我们可以配置Struts 2只处理以.do为后缀的请求路径:


struts2入门(三)
接受请求参数处理采用基本类型接收请求参数(get/post)在Action类中定义与请求参数同名的属性,struts2便能自动接收请求参数并赋予给同名属性。
请求路径: http://localhost:8080/test/view.action?id=78
public class ProductAction {
private Integer id;
public void setId(Integer id) {//struts2通过反射技术调用与请求参数同名的属性的setter方法来获取请求参数值
this.id = id;
}
public Integer getId() {return id;}
}
采用复合类型接收请求参数请求路径: http://localhost:8080/test/view.action?product.id=78
public class ProductAction {
private Product product;
public void setProduct(Product product) { this.product = product; }
public Product getProduct() {return product;}
}
Struts2首先通过反射技术调用Product的默认构造器创建product对象,然后再通过反射技术调用product中与请求参数同名的属性的setter方法来获取请求参数值。
类型转换的意义 对于一个智能的MVC框架而言,不可避免的需要实现类型转换.因为B/S(浏览器/服务器)结构应用的请求参数是通过浏览器发送到服务器的,这些参数不可能有丰富的数据类型,因此必须在服务器端完成数据类型的转换

MVC框架是一个表现层解决方案,理应提供类型转换的支持,Struts2提供了功能非常强大的类型转换支持
struts2入门(三)
自定义类型转换器

java.util.Date类型的属性可以接收格式为2009-07-20的请求参数值。但如果我们需要接收格式为20091221的请求参数,我们必须定义类型转换器,否则struts2无法自动完成类型转换。

import java.util.Date;public class HelloWorldAction {private Date createtime;public Date getCreatetime() {return createtime;}public void setCreatetime(Date createtime) {this.createtime = createtime;}}public class DateConverter extends DefaultTypeConverter {                @Override  public Object convertValue(Map context, Object value, Class toType) {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");try { if(toType == Date.class){//当字符串向Date类型转换时String[] params = (String[]) value;// Request.getParameterValues() return dateFormat.parse(params[0]);}else if(toType == String.class){//当Date转换成字符串时Date date = (Date) value;return dateFormat.format(date);}} catch (ParseException e) {}return null;}}

将上面的类型转换器注册为局部类型转换器:

在Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是Action的类名,后面的-conversion.properties是固定写法,对于本例而言,文件的名称应为HelloWorldAction-conversion.properties 。在properties文件中的内容为:

属性名称=类型转换器的全类名

对于本例而言, HelloWorldAction-conversion.properties文件中的内容为:

createtime= cn.csdn.conversion.DateConverter

将上面的类型转换器注册为全局类型转换器:

在WEB-INF/classes下放置xwork-conversion.properties文件 。在properties文件中的内容为:

待转换的类型=类型转换器的全类名

对于本例而言, xwork-conversion.properties文件中的内容为:

java.util.Date= cn.csdnconversion.DateConverter




读书人网 >软件架构设计

热点推荐