当前位置:编程学习 > JAVA >>

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
作者:hyljava

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,