RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Simplify Your Web App Development Using the Spring MVC Framework : Page 4

Struts is in fairly widespread use in the Java world, but the Spring MVC framework promises to provide a simpler alternative to Struts for separating presentation layer and business logic. Learn how to build a simple stock trading Web application using Spring's MVC framework.

The Logon Page
Now you know how to create a page with dynamically updated content, but what good is a Web application that has no way to capture user input from an HTML form? We could implement the Controller interface in order to do form processing, but that would require us to do a lot of manual processing or request parameters and storing things on the session. Personally, I've hand coded more form-processing code in this fashion than I ever hope to again. Thus, out of sheer laziness, I will show you how Spring simplifies form handling via the SimpleFormController by building a logon page.

Listing 4 shows the logon JSP. The <spring:bind> tag and the <spring:hasBindErrors> tag are in the spring.tld tag library descriptor that comes with Spring. Add this file to your WEB-INF directory and then add the following to your web.xml and include.jsp files.


<%@ page session="false"%>

<%@ taglib prefix="core" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<%@ taglib prefix="str" uri="http://jakarta.apache.org/taglibs/string-1.1" %>
<%@ taglib prefix="spring" uri="/spring" %>
The bind tag tells Spring to bind the enclosed form element to the bean property specified by the path attribute. For example the username input parameter will be bound to the username field on a bean named "credentials." The credentials bean is a special type of bean called a "command" or a "form-backing bean." Spring uses command beans for data binding while processing forms. The name used to reference this bean and its class type is defined in the tradingapp-servlet.xml file in the logonForm bean (see Listing 5).

I've also added a new entry to the handler mapping to point to our logon form when the user navigates (or is routed) to the logon.htm URL. The logon form has several properties:

  • commandClass—the class of the object that will be used to represent the data in this form.
  • commandName—the name of the command object.
  • sessionForm—if set to false, Spring uses a new bean instance (i.e. command object) per request, otherwise it will use the same bean instance for the duration of the session.
  • validator—a class that implements Spring's Validator interface, used to validate data that is passed in from the form.
  • formView—the JSP for the form, the user is sent here when the controller initially loads the form and when the form has been submitted with invalid data.
  • successView—the JSP that the user is routed to if the form submits with no validation errors.
Here is the code for the Controller:

package com.devx.tradingapp.web;

import javax.servlet.ServletException;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

public class LogonFormController extends SimpleFormController {
    public ModelAndView onSubmit(Object command) throws ServletException {
        return new ModelAndView(new RedirectView(getSuccessView()));

There's really not much to it. All the FormController does is forward to the success view. The validator takes care of authenticating the user. If the user provides an invalid username or password, the validator will return the user to the form and display an error message. Listing 6 shows the code for the validator.

The validator has a supports method and a validate method. The supports method is called to see if the validator supports a given object type. We want our validator to be able to validate objects of the type Credentials, because that is the command object that we are using for this form.

The validate method does some checks and calls the rejectValue method on the Errors class if validation fails. This method takes four parameters: the name of the field that failed validation, the key value of the error message that exists in a resource file (I'll explain in a second), a string array of values to substitute into the error message in the resource file, and the default error message that should be displayed if the resource file cannot be found. If any errors are found on the Errors object after validate is done running, Spring will forward control back to the original form JSP so that the errors can be displayed.

You may have noticed above that I also added a ResourceBundleMessageSource bean definition to the tradingapp-servlet.xml file. This is a reference to a properties file that contains application messages that can be defined and accessed throughout the application. These messages can be accessed in many ways, including being directly accessed from JSPs or, as we just saw, by the Errors object to provide error messages. This file must exist in the top level of your classpath, so I just put it in the WEB-INF/classes directory. I've jumped the gun and included all the error messages that our application will use in the file:

error.login.not-specified=User credentials not specified (try guest/guest).
error.login.invalid-user=Username not valid, try 'guest'
error.login.invalid-pass=Password not valid, try 'guest'
error.trade.insufficient-funds=You do not have enough money to place this order
error.trade.not-enough-shares=You do not have that many shares
error.trade.dont-own=You don't own this stock
error.trade.invalid-symbol=Invalid ticker symbol: {0}
Here is the code for the infamous Credentials class (the command/form-backing object):

package com.devx.tradingapp.business;

public class Credentials {
    private String username;

    private String password;

    public String getPassword() {
        return password;

    public void setPassword(String password) {
        this.password = password;

    public String getUsername() {
        return username;

    public void setUsername(String username) {
        this.username = username;

Now you can change the index.jsp page in the root directory to point to logon.htm.

<%@ include file="/WEB-INF/jsp/include.jsp" %>

<core:redirect url="/logon.htm"/>
Now if you load index.jsp, you will see the logon page, as shown in Figure 4.

Figure 4. Validating: When the logon page does not validate correctly, the user is returned to the form page where the validation errors are displayed.

In summary, here is the flow through this form:

  1. The user goes to the logon.htm page.
  2. He is routed to the dispatcher servlet (because all .htm pages are directed to the dispatcher Servlet).
  3. The DispatcherServlet loads the tradingapp-servlet.xml file and routes the user to the LogonFormController.
  4. The LogonFormController loads the command bean (form-backing object) and routes the user to the page defined in the formView (logon.jsp).
  5. The user fills out the form and submits it.
  6. The user is directed back to the controller and in turn the validator.
  7. If the validator fails, the user is sent back to the form view and error messages are displayed (back to logon.jsp and step 5).
  8. If the validator doesn't fail, the controller's onSubmit method is called and the user is forwarded to the successView JSP (portfolio.jsp).

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date