Spring MVC Tutorial With Command Object on Eclipse and Tomcat

This article is continuation of the Spring MVC Tutorial with Eclipse and Tomcat. Now, let us add the next practical aspect to our code – form or what Spring MVC calls it – command object. If you remember the starting days of servlet, or days of unavailability of frameworks like Struts, Spring MVC, we used to retrieve the data submitted from a HTML page using HTTP request object. Some of you must have hated the chain of request.getAttribute(..) calls. This problem is addressed by these presentation tier frameworks and we have a POJO, some people call it Java bean, associated with the html. The framework will do the job of retrieval of attributes and setting those in POHO for us, and we get an instance of POJO, populated with the values entered by user. The first article did not contain any handling of form/command object (now onwards we call it as command object only). But in practical scenario, we will mostly have the command objects. These changes we are going to make to the code in previous example.

Changes to Introduce Command Objects:

Add New Jars:

We are going to use Spring’s ‘form’ tag library and Jstl’s core tag library. For the JSTL core tag library, I have included following two jars. You can add other Jstl tag libraries also. Add these libraries to ‘WEB-INF/lib’ directory and refresh the project in eclipse. Add these libraries to the project libraries through ‘Right Click on Project’ – properties – Java Build Path – Libraries – Add Jars.

jstl.jar

standard.jar

Java Changes:

On Java side, we need to add two classes. First is HelloVisitorController, it handles our HTML form submission, and redirects to a new page. Second is the command object – Visitor. It has the three attributes to manage our functionality. Ok, the functionality is – We ask user to enter first name and last name on first screen, and on submission, we concatenate those two and present complete name on second screen. Elementary thing right? No complex functional business.

Next we change the HelloWorldController to fulfill the requirement of Spring MVC with respect to command object; we create an instance of the command object and return it.

Here is our first new class, notice the change in this controller. It extends from SimpleFormController to get support for the command object handling. I found extending from this class enough to give most of the features required for a command object based application. We are not making this change to the HelloWorldController because this controller does not expect command object to be available in its submission handler method.

HelloVisitorController.java

package com.myorg.springmvctutorial.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.myorg.springmvctutorial.web.command.Visitor;

public class HelloVisitorController extends SimpleFormController {

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
	}

	protected ModelAndView disallowDuplicateFormSubmission(
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		BindException errors = getErrorsForNewForm(request);
		errors.reject("duplicateFormSubmission", "Duplicate form submission");
		return showForm(request, response, errors);
	}

	protected final ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object commandObject,
			BindException errors) throws Exception {
		try {
			Visitor visitor = (Visitor)commandObject;
			logger.trace("First Name" + visitor.getFirstName()+
					"Last Name:" + visitor.getLastName());
			visitor.setCompleteName(visitor.getFirstName() + " "
					+ visitor.getLastName());
			Map dataMap = new HashMap();
			dataMap.put("visitor", visitor);
			return new ModelAndView("hellovisitor.jsp", dataMap);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw e;
		}
	}

}

Next is the command object. I hope you will override the hashCode, equals and toString methods as required.

 

Visitor.java

package com.myorg.springmvctutorial.web.command;

public class Visitor {
	private String firstName = "";
	private String lastName = "";
	private String completeName = "";

	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String aFirstName) {
		this.firstName = aFirstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String aLastName) {
		this.lastName = aLastName;
	}
	public String getCompleteName() {
		return completeName;
	}
	public void setCompleteName(String completeName) {
		this.completeName = completeName;
	}

}

Now the changed HelloWorldController.java.

 

HelloWorldController.java

package com.myorg.springmvctutorial.web.controller;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.myorg.springmvctutorial.web.command.Visitor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HelloWorldController implements Controller {
	protected final Log logger = LogFactory.getLog(getClass());

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		logger.info("Return View");
		Map dataMap = new HashMap();
		Visitor visitor = new Visitor();
		dataMap.put("visitor", visitor);
		return new ModelAndView("helloworld.jsp", dataMap);
	}
}

JSP Changes:

We add hellovisitor.jsp. It shows the visitor.completeName using ‘out’ element of Jstl core tag library.

 hellovisitor.jsp

In helloworld.jsp we add the first name and last name text fields, and button which submits the form. 

 helloworld.jsp

Changes to the Configurations:

We need to add the new controller and the command object association to it. I am going to keep this command object to request scope, hence not adding the sessionForm property. Add this bean element to our SpringMVCTutorial-servlet.xml.

SpringMVCTutorial-servlet.xml

See It Working:

This is how the first page hello world will look like with changes after running it on tomcat (as directed in previous tutorial) and calling the shown url (http://localhost:8080/SpringMVCTutorial/helloworld.htm).

 WithformhelloworldPage

On Submit button press, here is our complex job done!!!

 AfterSubmitButtonPress

  • Share/Bookmark
Spring, Tech Notes

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

11 Responses to “Spring MVC Tutorial With Command Object on Eclipse and Tomcat”

Leave Comment

(required)

(required)