This month, I decided to go more in-depth with Spring and SpringMVC and model the web services for a CMS/Shopping Cart system. With Spring, Tomcat, XOM, and JUnit, I was able to speedily throw together a modular, DI-driven web service that implemented a simple web service interface without needing to worry about database details or request mapping.
Specifically, Spring’s MultiActionController and XOM’s XML building utilities let me write the minimal AccountController given below.
public class AccountController extends MultiActionController
{
private AccountManagementService accountManagementService;
public ModelAndView login( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
String username = StringEscapeUtils.escapeHtml( request.getParameter( "username" ) );
String password = StringEscapeUtils.escapeHtml( request.getParameter( "password" ) );
Document xmlDoc = accountManagementService.login( username, password );
response.getWriter().println( xmlDoc.toXML() );
return null;
}
public ModelAndView register( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
String username = StringEscapeUtils.escapeHtml( request.getParameter( "username" ) );
String password = StringEscapeUtils.escapeHtml( request.getParameter( "password" ) );
Document xmlDoc = accountManagementService.register( username, password );
response.getWriter().println( xmlDoc.toXML() );
return null;
}
public void setAccountManagementService( AccountManagementService accountManagementService )
{
this.accountManagementService = accountManagementService;
}
}
The URL mapping for service requests was also dead-simple:
<bean id="urlMappingDeployment" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/login.do">accountController</prop>
<prop key="/register.do">accountController</prop>
<prop key="/getInventory.do">inventoryController</prop>
<prop key="/updateInventory.do">inventoryController</prop>
</props>
</property>
</bean>
By utilizing Spring, I saved reams of code, although using a more expressive language like Groovy with Grails may have been quicker and more expressive. At any rate, I’m off to go learn about XSLT. Cheers.