2010-03-23 44 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