Global String.trim() function
I found that <conversion-for-class>java.lang.String</conversion-for-class> is not applicable (the converter is not called)
because of this, users can submit values with spaces, which gets set into the backing bean and goes down the DB, where it breaks
Is there a pattern for solving this in JSF (that is trimming all submitted strings) without having to write String.trim() in all the getter/setters? There are too many beans where this would need to be done
Definitely, putting the trim() logic in bean is not comfortimg (at least to me)
Turns out validators cannot SET the values (tried that to try luck)
Second thing i am trying is to setup a phaseListener to get request variables as they are submitted and trimming them
I am thinking of doing this in UPDATE_MODEL_VALUES phase, but don't know where i can set the trimmed values and how
Can anyone help?
Thanks!
Message was edited by:
jesef
[975 byte] By [
jesefa] at [2007-11-27 2:52:46]

# 2
Using a PhaseListener is a nice idea. I've just played somewhat with it, here is the snippet, I am almost sure that it will be useful for others:package mypackage.phaselisteners;
import java.util.List;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
public class TrimUIInputStrings implements PhaseListener {
public PhaseId getPhaseId() {
return PhaseId.UPDATE_MODEL_VALUES;
}
public void beforePhase(PhaseEvent event) {
FacesContext context = event.getFacesContext();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
// Only handle POST.
if ("POST".equalsIgnoreCase(request.getMethod())) {
trimUIInputStrings(context.getViewRoot().getChildren());
}
}
public void afterPhase(PhaseEvent event) {
// Do nothing.
}
private void trimUIInputStrings(List<UIComponent> children) {
for (UIComponent child : children) {
// Only handle UIInput components.
if (child instanceof UIInput) {
UIInput input = (UIInput) child;
Object value = input.getValue();
// Only handle Strings.
if (value != null && value instanceof String) {
input.setValue(((String) value).trim());
}
}
if (child.getChildCount() > 0) {
// Loop through it's children.
trimUIInputStrings(child.getChildren());
}
}
}
}
The faces-config.xml declaration:<lifecycle>
<phase-listener>mypackage.phaselisteners.TrimUIInputStrings</phase-listener>
</lifecycle>