February 16, 2019
Hot Topics:

Developing J2EE Applications Using Hibernate Annotations and Spring MVC

  • January 12, 2006
  • By M. M. Islam Chisty
  • Send Email »
  • More Articles »

Step 3: The Service, or Business Logic, Layer

In this step, you will need to create service objects and wire these classes.

Create service objects

Click these links to get the source codes for the interface MyObjectService.java and the implementation class MyObjectServiceImpl.java. These should be under the org.annotationmvc.service package:

If you look at these two classes, you will find that these are similar to the MyObjectDao and MyObjectDaoImpl objects with their method definitions, except for the class names. These classes basically hold the business rules. For data manipulation, it uses the DAO object to communicate at the persistence layer. For example, consider the findMyObjectById(...) method. To fetch an object by its object id, it simply invokes the MyObjectDAO's findMyObjectById method. Other methods do not need further explanation.


Create a file named applicationContext-service.xml and place it under the "springappwarWEB-INF" directory. (Click here to get the applicationContext-service.xml file.) Some code snippets from this file are seen below:

<bean id="myObjectService" parent="txProxyTemplate">
<property name="target">
<bean class="org.annotationmvc.service.MyObjectServiceImpl">
<property name="myObjectDao">
<ref bean="myObjectDao" />


Note the bean with id "Service". The setter injection is identified from the property name "myObjectDao", which you have declared within the MyObjectServiceImpl class's setMyObjectDao(MyObjectDao myObjectDao) method.

Step 4: Creating the UI Layer

For this step, you will be following Spring's MVC pattern for this application. Spring provides a very clean division between controllers, JavaBean models, and views. You can use any object as a command or form object; there's no need to implement an interface or derive from a base class. Spring's data binding is highly flexible; for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. So, you don't need to duplicate your business objects' properties as Strings in your form objects just to be able to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects. This is another major difference to Struts, which is built around required base classes like Action and ActionForm—for every type of action.

Okay, enough of theory, let's do some real work now:

Create a Controller object

(Click here to get the Controller object, MyObjectController.java, used in this example.) This should be placed under the org.annotationmvc.web package. The Controller object is used to display read-only data. You cannot use it for data manipulation. It returns a ModelAndView object, which returns both a model (for example, the ArrayList containing the list of objects) and a view (as in the name of the JSP page).

For instance, if you look at the following example you will find that a model, in this case, is represented by the string "myObjectModel". This actually refers to a list of all MyObjectVO objects (the list of POJOs), returned by the third parameter—in other words, myObjectService.getAllMyObjectVOs(). A view object, on the other hand, actually refers to the JSP page, which is represented by the string "ViewAllMyObjects". This would simply be interpreted as "ViewAllMyObjects.jsp", which is explained later in this article.

package org.annotationmvc.web;

public class MyObjectController implements Controller {

   public ModelAndView handleRequest(HttpServletRequest request,
          HttpServletResponse response) throws Exception {
             return new ModelAndView("ViewAllMyObjects",

   public void setMyObjectService(MyObjectService
                                  myObjectService) {
      this.myObjectService = myObjectService;



Once your controller object is implemented, you next need to define it within your action-servlet.xml file. To do this, create a file named action-servlet.xml under the "WEB-INF" directory or, click here to download the action-servlet.xml. The following examples are some code snippets for this file:


<bean id="viewResolver"
   <property name="viewClass">
   <property name="prefix"><value>/jsp/</value></property>
   <property name="suffix"><value>.jsp</value></property>

<!-- Custom controller objects -->
<bean id="moController"
   <property name="myObjectService">
      <ref bean="myObjectService"/>

<bean id="urlMapping"
   <property name="mappings">
   <prop key="/test.html">moController</prop>


The following list explains some of the properties defined in the previous configuration file:

  • The "prefix" property defines that your JSP pages will reside under the war/jsp directory.
  • The "suffix" property defines that all views returned by the controller will be appended with a .jsp extension. For example, the MyObjectController returns a view named "ViewAllMyObjects". By using the suffix property, this will actually be interpreted as ViewAllMyObjects.jsp and search for a JSP page named ViewAllMyObjects.jsp under the war/jsp directory. This means that you must have a JSP file with this name. If no page with this name is found, an exception will be generated during runtime.
  • The bean with id "moController" defines the fully qualified name of your controller class.
  • The property key "/test.html" is actually a dummy name. If you provide this name with your URL, it will actually call the keyvalue 'moController'—in other words, org.annotationmvc.web.MyObjectController object—which, in turn, will return the view object in success.

(If you are interested in learning more about Spring's Controller objects, you can check this URL at http://www.springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step-Part-2.html.)

Create a SimpleFormController object

A SimpleFormController object is used for data manipulation (insert, update, delete). It lets you specify a command object, a viewname for the form, a viewname for the page you want to show the user when form submission has succeeded, and more. SimpleFormController calls two distinct set of methods: one for GET request methods to prepare the form for display, and one for POST request methods to process the information extracted from the form. This corresponds with how most Web applications work: a GET signifies an edit, whereas a POST signifies a save or delete. SimpleFormController is a concrete FormController that provides configurable form and success views, and an onSubmit chain for convenient overriding. It automatically resubmits to the form view in case of validation errors, and renders the success view in case of a valid submission.

Here are the two useful methods of the SimpleFormController object:

  • The onSubmit method, which is used for data insert, update, and delete operations.
  • The formBackingObject method, which is used to create an empty object for inserting data and a populated object for editing data.

Now, create a MyObjectFormController object within the org.annotationmvc.web package or, you can click here to download MyObjectFormController.java. Code snippets from this example are seen below:

package org.annotationmvc.web;

public class MyObjectFormController extends SimpleFormController {

   public MyObjectService getMos() {
      return mos;

   public void setMos(MyObjectService mos) {
      this.mos = mos;

   public ModelAndView onSubmit(HttpServletRequest request,
                                HttpServletResponse response,
                                Object cmd, BindException errors)
   throws Exception {

      MyObjectVO myObjectVO = (MyObjectVO) cmd;
      if (null != request.getParameter("delete")) {
      } else if (null != request.getParameter("update")) {
      } else if (null != request.getParameter("add")) {
      return new ModelAndView(new RedirectView(getSuccessView()));

   protected Object formBackingObject(HttpServletRequest
   throws ServletException {
      String id = request.getParameter("id");
      if (null != id && !id.equals("")) {
         return mos.findMyObjectById(Integer.parseInt(id));
      return new MyObjectVO();



Define the MyObjectFormController object in the action-servlet.xml configuration file. You can get the updated action-servlet.xml file here.

As you can see, two views are defined in the action-servlet.xml file, one for the empty form and one for the successful form processing. The latter is called the success view. To restrict users from direct access to any JSP pages, the URL that is used is only externally reachable. This means that the "MyObjectForm.html" is used as the redirect URL, for example. It refers to the MyObjectFormController object, which finally returns the MyObjectForm.jsp page. This can be depicted as follows:

--> MyObjectFormController (referred by prop key value
--> MyObjectForm (referred by the property value
                  "formView") -->
MyObjectForm.jsp (interpreted)

(For details on Spring's SimpleFormController object, please check this URL: http://www.springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step-Part-3.html.)

Page 3 of 4

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

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