hyljava

Struts2自定义局部类型转换器

一、AddUAction
package com;
import java.util.Date;
public class AddUAction {
 private Date birdate;
 public Date getBirdate() {
  return birdate;
 }
 public void setBirdate(Date birdate) {
  this.birdate = birdate;
 }
 public String addU(){
  System.out.println(birdate);
  return  "ok";
 }
}
二、struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="te" namespace="/te" extends="struts-default">
 <action name="teMan" class="com.AddUAction" method="addU">
 <result name="ok">/index.jsp</result>
 </action>
</package>
</struts>   

三、DateConverter
package com;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Map;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
public class DateConverter extends DefaultTypeConverter {
 @Override
 public Object convertValue(Map<String, Object> context, Object value,
   Class toType) {
  SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
  try{
   if(toType==Date.class){
    String[] params=(String[]) value;
    return dateFormat.parse(params[0]);
   }else{
    Date date=(Date) value;
    return dateFormat.format(date);
   }
  }catch (Exception e) {
   return null;
  }
 }
}

四、AddUAction-conversion.properties
birdate=com.DateConverter
五、包结构



六、在地址栏输入
http://localhost:8080/test/te/teMan!addU?birdate=20010205

七、结果会在jsp页面显示出来
This is my JSP page.
Mon Feb 05 00:00:00 CST 2001


posted on 2012-07-20 14:38 何云隆 阅读(1341) 评论(0)  编辑  收藏 所属分类: Struts2


只有注册用户登录后才能发表评论。


网站导航: