2010-03-23 49 views
6

我使用struts2開發web應用程序。我想改善從表單中獲取字符串。爲此需要修剪所有字符串,如果獲得的字符串爲空,則將字段設置爲nullstruts2修剪從表格中獲取的所有字符串

爲此,我創建了StringConverter

public class StringConverter extends StrutsTypeConverter { 

    @Override 
    public Object convertFromString(Map context, String[] strings, Class toClass) { 
     if (strings == null || strings.length == 0) { 
      return null; 
     } 

     String result = strings[0]; 
     if (result == null) { 
      return null; 
     } 

     result = result.trim(); 
     if (result.isEmpty()) { 
      return null; 
     } 
     return result; 
    } 

    @Override 
    public String convertToString(Map context, Object object) { 
     if (object != null && object instanceof String) { 
      return object.toString(); 
     } 
     return null; 
    } 
} 

接下來,我添加了一行xwork-conversion.properties

java.lang.String=com.mypackage.StringConverter 

這就是所有。但是我沒有得到理想的結果。


convertToString()方法在jsp構建窗體時調用,但convertFromString()不調用。

我做錯了什麼?我怎樣才能以另一種方式獲得相同的行爲?

請,沒有提供解決方案,如:

  1. 刪除使用JavaScript這樣的表單元素的值。
  2. 創建util方法,它將使用反射。然後爲每個表單bean調用它。

在此先感謝, 阿列克謝。

+1

同樣的事情發生在我身上。 – 2012-02-21 18:53:53

回答

1

我不做Struts2,但類似的問題已經在2006年的JSF版本1.2(JSF是Sun的MVC框架,Struts2的競爭對手)中體現出來。在JSF以及「設計」中,轉換爲String是不可能的。較老的JSF版本用於檢查目標類型是否等於java.lang.String,然後僅在模型中設置請求參數值而不嘗試轉換它(因爲請求參數值已獲得爲String)。如果目標類型不同,則它將定位並運行任何關聯的轉換器以將其轉換爲期望的目標類型(不是String)。自JSF 1.2以來,他們通過刪除目標類型的檢查並以任何方式定位轉換器來修復它。

如果Struts2中存在類似的功能/錯誤,我不會感到驚訝。如果還沒有關於該問題的問題/錯誤報告,我會環顧他們的主頁,否則發佈一個。

3

似乎對我來說。你確定convertFromString甚至沒有被調用?

你可能會嘗試的另一種方法是編寫一個修剪所有參數的攔截器(經常需要這樣做)。

5

你會在StrutsTypeConverter類的代碼中找到答案。基本上,在這個級別上,類型轉換器框架不知道數據是從「來自」還是「到」用戶,它只知道它正在從一種類型(字符串)轉換爲另一種類型(也是字符串) 。並且由於它首先檢查「to」類型,它將總是調用convertToString 。簡而言之,當前版本的Struts(2.1.x是我使用的)不支持並且不支持字符串到字符串類型轉換器。因爲他們畢竟是類型的轉換器,你可以說這是設計。

我也在尋找一種方法來實現類似的結果,但還沒有找到一個非常好的解決方案。可能最「正確」的方法是編寫攔截器(如提到的@leonbloy)。有幾種方法可以解決這個問題,最直接的方法是在所有請求參數設置在動作之前(即在執行「params」攔截器之前)。

+0

這個解決方案如何? http://stackoverflow.com/a/12989407/369587 – webdevbyjoss 2014-04-11 14:20:14

0

this blog推薦,我在代碼中做了一個小修改,它工作正常。這不是任何與struts相關的實用程序,但您可以實現您的需要。

這裏是實用類:

package com.company.project.common.helpers; 

import java.io.Serializable; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 

/** 
* 
* <b>File Name :</b> <i>BeanUtils.java</i> <br> 
* <b>Description :</b> 
* <p> 
* This class contains the activities of skill program. <br/> 
* <br/> 
* <b>Copyright :</b> Copyright© yyyy description 
* </p> 
* <h1>Version History :</h1> 
* 
* Date : 20-06-2013<br/> 
* Description : First Draft 
* 
* @version 1.0.0.1 
* @since 1.0.0.0.1 
* @author visruth 
* 
*/ 
public class BeanUtils implements Serializable { 

    /** 
    * This method trims all String variables defined in the bean if they have 
    * corresponding getter setter methods. <br/> 
    * Eg : BeanUtils beanUtils=new BeanUtils();<br/> 
    * StudentVO studentVO=new StudentVO();<br/> 
    * studentVO.setName(" foo ");<br/> 
    * studentVO.setAddress(" bar ");<br/> 
    * beanUtils.trimAllStrings(studentVO);<br/> 
    * System.out.println(studentVO.getName());//prints foo<br/> 
    * System.out.println(studentVO.getAddress());//prints bar<br/> 
    * 
    * @param beanObject 
    * @throws Exception 
    *    If a variable has its getter method defined but not setter 
    *    method will throw NoSuchMethodException instance as 
    *    Exception. 
    * @author visruth 
    */ 
    public void trimAllStrings(Object beanObject) throws Exception { 
     Exception noSuchMethodException = null; 
     boolean throwNoSuchMethodException = false; 
     if (beanObject != null) { 

      Method[] methods = null; 

      try { 
       methods = beanObject.getClass().getMethods(); 
      } catch (SecurityException e) { 
       throw new Exception(e); 
      } 

      if (methods != null) { 

       for (Method method : methods) { 

        String methodName = method.getName(); 

        if (!methodName.equals("getClass")) { 

         String returnType = method.getReturnType().toString(); 
         String commonMethodName = null; 

         if (methodName.startsWith("get") 
           && "class java.lang.String".equals(returnType)) { 

          commonMethodName = methodName.replaceFirst("get", 
            ""); 
          String returnedValue = null; 

          try { 
           returnedValue = (String) method 
             .invoke(beanObject); 
          } catch (IllegalArgumentException e) { 
           e.printStackTrace(); 
           throw e; 
          } catch (IllegalAccessException e) { 
           e.printStackTrace(); 
           throw e; 
          } catch (InvocationTargetException e) { 
           e.printStackTrace(); 
           throw e; 
          } 

          if (returnedValue != null) { 

           StringBuilder setterMethodName = new StringBuilder(); 
           setterMethodName.append("set"); 
           setterMethodName.append(commonMethodName); 
           Method setterMethod = null; 

           try { 
            setterMethod = beanObject 
              .getClass() 
              .getMethod(
                setterMethodName.toString(), 
                String.class); 
            if (setterMethod != null) { 
             if(returnedValue.isEmpty()) { 
              Object o=null; 
              setterMethod.invoke(beanObject, o); 
             } else { 
              setterMethod.invoke(beanObject, 
                (returnedValue.trim()));  
             }          
            } 
           } catch (SecurityException e) { 
            e.printStackTrace(); 
            throw e; 
           } catch (NoSuchMethodException e) { 
            e.printStackTrace(); 
            if (!throwNoSuchMethodException) { 
             noSuchMethodException = e; 
            } 
            throwNoSuchMethodException = true; 
           } catch (IllegalArgumentException e) { 
            e.printStackTrace(); 
            throw e; 
           } catch (IllegalAccessException e) { 
            e.printStackTrace(); 
            throw e; 
           } catch (InvocationTargetException e) { 
            e.printStackTrace(); 
            throw e; 
           } 
          } 
         } 
        } 
       } 
      } 
     } 

     if (throwNoSuchMethodException && noSuchMethodException != null) { 
      throw noSuchMethodException; 
     } 
    } 

} 

嘗試:

package com.company.project.common.valueobject; 

import java.io.Serializable; 

import com.company.project.common.helpers.BeanUtils; 

public class DetailsVO implements Serializable { 

    private static final long serialVersionUID = 6378955155265367593L; 
    private String firstName; 
    private String lastName; 
    private String address; 
    private double latitude; 
    private double longitude; 

    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    public String getLastName() { 
     return lastName; 
    } 

    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 

    public String getAddress() { 
     return address; 
    } 

    public void setAddress(String address) { 
     this.address = address; 
    } 

    public double getLatitude() { 
     return latitude; 
    } 

    public void setLatitude(double latitude) { 
     this.latitude = latitude; 
    } 

    public double getLongitude() { 
     return longitude; 
    } 

    public void setLongitude(double longitude) { 
     this.longitude = longitude; 
    } 

    public static void main(String[] args) { 
     BeanUtils beanUtils = new BeanUtils(); 

     DetailsVO profileVO = new DetailsVO(); 

     profileVO.setFirstName(""); 
     profileVO.setLastName("  last name    "); 
     profileVO.setAddress("  address   "); 

     System.out.println(profileVO.getFirstName()); 
     System.out.println(profileVO.getLastName()); 
     System.out.println(profileVO.getAddress()); 

     try { 
      beanUtils.trimAllStrings(profileVO); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     System.out.println(profileVO.getFirstName()); 
     System.out.println(profileVO.getLastName()); 
     System.out.println(profileVO.getAddress()); 
    } 
} 

而且給出了這樣的輸出:

 last name    
     address   
null 
last name 
address