Expert Spring MVC and Web Flow

(Dana P.) #1
public void setAsText(String text) throws IllegalArgumentException {
if (! StringUtils.hasText(text)) {
throw new IllegalArgumentException("text must not be empty or null");
}

Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
PhoneNumber phoneNumber = new PhoneNumber();
phoneNumber.setAreaCode(matcher.group(1));
phoneNumber.setPrefix(matcher.group(2));
phoneNumber.setSuffix(matcher.group(3));

setValue(phoneNumber);
} else {
throw new IllegalArgumentException(text +
" does not match pattern " + pattern);
}
}

@Override
public String getAsText() {
return getValue().toString();
}

}

The HTML form with a phone number input field would look something like that in
Listing 6-34.

Listing 6-34.PhoneNumber HTML Form

<form>
<p>
Phone Number: <input type="text" name="phoneNumber" /> (XXX) XXX-XXXX
</p>
<p><input type="submit" /></p>
</form>

The following unit test, Listing 6-35, simulates the HTTP request with a value of (222)
333-4444as the user’s phone number.

Listing 6-35.PhoneNumberEditor Binding Unit Test

protected void setUp() throws Exception {
bean = new PhoneNumberCommand();
request = new MockHttpServletRequest();
binder = new ServletRequestDataBinder(bean, "bean");

144 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf