Although this is an old question, if you still get tripped on this then here is how I solved this.
Say we have this form src/main/webapp/view/greet-form.html (I am using Thymeleaf)
<form action="/something" th:attr="action=@{/greet}" method="post" th:object="${student}">
<p><strong>Enter your first name</strong></p>
<p><input type="text" th:field="*{firstName}" th:value="*{firstName}"> <span class="error">*</span><br />
<span class="error_message" th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"></span></p>
<p><strong>Enter your secret code</strong></p>
<p><input type="text" th:field="*{secretCode}" th:value="*{secretCode}"> <span class="error">*</span><br />
<span class="error_message" th:if="${#fields.hasErrors('secretCode')}" th:errors="*{secretCode}"></span></p>
<p><input type="submit" value="Submit"></p>
</form>
When the form is submitted, we want Spring to trim the value of firstName but leave secretCode as it is.
This is our form backing class, defined in src/main/java/Student.java. The trick is not to use String type for secretCode but some other custom type. This way, StringTrimmerEditor will not be used for the secretCode and the data will not be trimmed.
public class Student {
private String firstName;
private SecretString secretCode;
public Student() {
//
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public SecretString getSecretCode() {
return secretCode;
}
public void setSecretCode(SecretString secretCode) {
this.secretCode = secretCode;
}
}
Here is the definition of SecretString in src/main/java/SecretString.java
public class SecretString {
private String secret;
public SecretString() {
secret = "";
}
public SecretString(String secret) {
//mandatory null check
secret = (secret == null)? "" : secret;
this.secret = secret;
}
@Override
public String toString() {
return secret;
}
}
But now Spring will complain about not being able to convert String to SecretString. This can be solved with a custom property editor or a custom converter (if you are using Spring 3+). I used a custom converter like this.
First define the code in src/main/java/SecretStringConverter.java
import org.springframework.core.convert.converter.Converter;
public class SecretStringConverter implements Converter<String, SecretString> {
@Override
public SecretString convert(String source) {
return new SecretString(source);
}
}
Then register our converter class with a conversion-service factory bean (I am using src/main/webapp/WEB-INF/spring-mvc-demo-servlet.xml)
<context:component-scan base-package="your package" />
<mvc:annotation-driven conversion-service="app_conversion_service"/>
<bean id="app_conversion_service" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="SecretStringConverter"></bean>
</list>
</property>
</bean>