一、自定義類型轉換器
創建一個類繼承com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter或繼承該類的子類org.apache.struts2.util.StrutsTypeConverter
- public class DateConversion extends StrutsTypeConverter {
-
- @Override
- public Object convertFromString(Map context, String[] values, Class toClass) {
- // TODO Auto-generated method stub
- SimpleDateFormat sf=new SimpleDateFormat("yyyyMMdd");
- if(toClass==Date.class){
- try {
- return sf.parse(values[0]);
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }else if(toClass==String.class){
- return sf.format(values[0]);
- }
- return null;
- }
-
- @Override
- public String convertToString(Map context, Object o) {
- // TODO Auto-generated method stub
- return null;
- }
- }
1、將上面的類型轉換器注冊為局部類型轉換器:
在Action類所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是Action的類名,後面的-conversion.properties是固定寫法,PersonAction-conversion.properties:
屬性名=類型轉換器全類名;
- # syntax: <propertyName> = <converterClassName>
- birthday=org.han.util.DateConversion
或者封裝對象:
- public class PersonConversion extends StrutsTypeConverter {
-
- @Override
- public Object convertFromString(Map context, String[] values, Class toClass) {
- SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
- Person per = new Person();
- per.setName(values[0]);
- try {
- per.setBirthday(sf.parse(values[1]));
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return per;
- }
-
- @Override
- public String convertToString(Map context, Object o) {
- // TODO Auto-generated method stub
- return null;
- }
- }
action:
- @Namespace("/")
- public class PersonAction extends ActionSupport{
- private Person per;
- public Person getPer() {
- return per;
- }
-
- public void setPer(Person per) {
- this.per = per;
- }
-
- @Action(value="person",results={@Result(name="success",location="/index.jsp")})
- public String execute() throws Exception {
- // TODO Auto-generated method stub
- System.out.println(per.getBirthday());
-
- return SUCCESS;
- }
-
- }
jsp:
- <body>
- <form action="person.action" method="post">
- <input type="text" name="per" />
- <input type="text" name="per" />
- <input type="submit" value="提交"/>
- </form>
- </body>
- per=org.han.util.PersonConversion
2、將上面的類型轉換器注冊為全局類型轉換器:
在src下放置xwork-conversion.properties文件,該文件內容為:
待轉換的類型全類名=類型轉換器全類名;
- java.util.Date=org.han.util.DateConversion