An application I'm working on has a lot of data being passed from the client to the server. In past applications, we've always been cleaning up this data manually, one property at a time - sometimes in the save method, but more likely in the setter:
public void setFirstName(String firstName)
{
this.firstName = (firstName != null ? firstName.trim() : null);
}
Of course you could globalize this a touch:
public void setFirstName(String firstName)
{
this.firstName = StringUtils.nullSafeTrim(firstName);
}
Well, with the volume of properties in the system we didn't want to handle this every time. So, I found a neat little thing you can do with Struts2. There are classes in Struts2 which convert the request parameters into the type of the property on the bean.
Of course, everything except files come over the wire as text, so in reality converting to a String is as simple as unpacking it out of the array that is handed to you from the servlet container. But, in our case, we want to do a quick trim on the value before Struts2 hands it to the action. To do this you need to:
- Create a new class to do the conversion.
- Tell Struts2 to use this class to do the conversion.
Pretty simple, right?
Your new type conversion class needs to extend org.apache.struts2.util.DefaultTypeConverter, which is an abstract class. Here's what I came up with (I omitted a lot of unimportant code):
public class TrimmingStringConverter extends StrutsTypeConverter
{
@Override
public Object convertFromString(Map context, String[] values, Class toClass)
{
if (values != null && values.length > 0)
{
return values[0].trim();
}
return null;
}
@Override
public String convertToString(Map context, Object o)
{
if (o != null)
{
return o.toString();
}
else
{
return null;
}
}
@Override
public Object convertValue(Map context, Object o, Class toClass)
{
if (o == null)
{
return null;
}
else if (toClass == java.lang.String.class)
{
if (o instanceof String[])
{
String[] os = (String[]) o;
if (os.length > 0)
{
return os[0].trim();
}
}
return o.toString().trim();
}
return super.convertValue(context, o, toClass);
}
}
The convertValue() method is implemented in the parent, so you don't have to override it. However, this seems to be the method called when I was testing, so it's important that you do.
Next up, you need to tell Struts2 about your shiny new code. It's as simple as adding a new properties file to your classpath called xwork-conversion.properties. In that file you should add:
java.lang.String = path.to.your.TrimmingStringConverter
My quick testing showed that every single String that came in from user input was trimmed up.
If anyone knows of a better way, or improvements I can make, leave a comment.
Robert, how can one get in contact with you about this domain? The whois.net info is hidden. Thanks.
ReplyDeleteMy email is robert at iremote dot com.
ReplyDelete