xNow we continue on the next step (go through Part 1 before reading this). Part 2 will cover the front-end part for this application.
We need to make our project as web application. It require a WEB-INF folder and a web.xml file in it. Below is our web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
<servlet>
<servlet-name>training</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>training</servlet-name>
<url-pattern>*.page</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>training</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
We will define a DispatcherServlet (also known as a 'Front Controller'). It’s going to control where all our requests are routed based on information we will enter at a later point. This servlet definition also has an attendant <servlet-mapping/> entry that maps to the URL patterns that we will be using. We have decided to let any URL with '.page' and '.form' extension be routed to the 'training' servlet (the DispatcherServlet).
Spring provides many types of controller. In this tutorial, we will use only 2 of them (Controller and SimpleFormController). Controller is a base controller interface, representing a component that receives HttpServletRequest and HttpServletResponse like a HttpServlet but is able to participate in an MVC workflow. SimpleFormController is a concrete FormController implementation that provides configurable form and success views, and an onSubmit chain for convenient overriding.
Now we will look into the first controller. It’s a controller (will implement Controller) to provide a list of student to the view.
public class StudentListController implements Controller{
private AdministrationService administrationService;
public void setAdministrationService(AdministrationService administrationService) {
this.administrationService = administrationService;
}
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List students = administrationService.getAllStudent();
Map myModel = new HashMap();
myModel.put("students",students);
ModelAndView mv = new ModelAndView("student_list", "model", myModel);
return mv;
}
}
As you can see, we need to use the AdministrationService to retrieve the student data from database. Inside the controller, we just prepare a setter method for Spring to inject the instance. This controller will return ModelAndView to our view (page) called student_list. Our second controller is a controller (will implement SimpleFormController) that will handle an input from a form and process it. SimpleFormController implements the Controller interface but also is part of a hierarchy of various abstract controller-related classes. It can also automatically redirect the user to the default form view in case of errors and to a different (or same) view if the form submission is successful. Here it is.
public class StudentFormController extends SimpleFormController{
private String action;
private AdministrationService administrationService;
public void setAdministrationService(AdministrationService administrationService) {
this.administrationService = administrationService;
}
public void setAction(String action) {
this.action = action;
}
protected Map referenceData(HttpServletRequest req) throws Exception {
Map model = new HashMap();
model.put("action", action);
return model;
}
protected void doSubmitAction(Object obj) throws Exception {
if ("Update".equals(action)) {
administrationService.updateStudent((Student)obj);
} else if ("Delete".equals(action)){
administrationService.unregisterStudent((Student)obj);
} else {
administrationService.registerStudent((Student)obj);
}
}
protected void initBinder(HttpServletRequest req, ServletRequestDataBinder bind) throws Exception {
super.initBinder(req, bind);
}
protected Object formBackingObject(HttpServletRequest req) throws Exception {
if (("Update".equals(action))||("Delete".equals(action))) {
String id = req.getParameter("id");
return administrationService.getStudent(new Integer(id));
}
return super.formBackingObject(req);
}
}
The referenceData method used to return read-only data to form. We will pass 1 parameter to determine the operation of the form whether to add, update or delete. The initBinder method used to to register custom property editors. The formBackingObject method returns a command object that is used to hold the input data from the HTML form fields.
Next, we will create a file called 'training-servlet.xml' in the WEB-INF directory. This file contains the bean definitions (plain old Java objects) used by the DispatcherServlet. It is the WebApplicationContext where all web-related components go. The name of this file is determined by the value of the <servlet-name/> element from the 'web.xml' and appended wtih '-servlet'. This is the standard naming convention used with Spring’s Web MVC framework.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<import resource="classes/applicationContext.xml" />
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
</bean>
<bean name="/student_list.page" class="com.training.controller.StudentListController">
<property name="administrationService" ref="administrationService"></property>
</bean>
<bean name="/add_student.form" class="com.training.controller.StudentFormController">
<property name="administrationService" ref="administrationService"></property>
<property name="commandClass" value="com.training.Student"></property>
<property name="successView" value="success_page"></property>
<property name="formView" value="student_form"></property>
<property name="commandName" value="studentManagement"></property>
<property name="action" value="Add"></property>
</bean>
<bean name="/edit_student.form" class="com.training.controller.StudentFormController">
<property name="administrationService" ref="administrationService"></property>
<property name="commandClass" value="com.training.Student"></property>
<property name="successView" value="success_page"></property>
<property name="formView" value="student_form"></property>
<property name="commandName" value="studentManagement"></property>
<property name="action" value="Update"></property>
</bean>
<bean name="/delete_student.form" class="com.training.controller.StudentFormController">
<property name="administrationService" ref="administrationService"></property>
<property name="commandClass" value="com.training.Student"></property>
<property name="successView" value="success_page"></property>
<property name="formView" value="student_form"></property>
<property name="commandName" value="studentManagement"></property>
<property name="action" value="Delete"></property>
</bean>
</beans>
Now it’s ready to run.
Source code: Get it here
Reference:
- http://static.springframework.org/docs/Spring-MVC-step-by-step/index.html
- http://static.springframework.org/spring/docs/1.2.x/api/index.html
- http://static.springframework.org/spring/docs/2.5.x/reference/
- HADZRUL –
Posted by Bob Wedding on 28 May 2009 at 12:43 AM
Dear Hadzrul;
This Spring MVC tutorial was both very educational and useful. It showed how to use Spring MVC with a database and not just a temporary list; it also is useful for any type of list you might want, E-mail,address,phone,etc while ignoring the name “Student” for quick utilization before customizing the program for a particular purpose.
Thank you very much for providing the tutorial.
I am keeping Spring MVC and your Hibernate tutorials for reference to go along with Grails and Maven for my needs.
Thanks again;
B.W.
Posted by Hadzrul on 1 June 2009 at 10:38 AM
Hi Bob,
Thanks for your comment on my tutorial. I will try to put more tutorials (to be my reference also) in future. Been busy with my work until I have no time to update my blog with tutorials.
By the way, I’m glad to have a positive response from you.