Step 4: Add a Controller Class

In this step we will add a Spring Controller to manage guestbook web requests:

  • Open the [New Java Class] dialog box by right clicking the guest package node (in the [Package Explorer] window) and selecting New > Class.
  • The package name should be guest.
  • Enter GuestController as the class name - use exactly that case sensitive class name.
  • Click Finish to create the new Spring Controller class.

Now replace the content of the new source file with the following code:

package guest;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class GuestController {

    @Autowired
    private GuestDao guestDao;

    @RequestMapping(value="/guest")
    public ModelAndView guestbook(HttpServletRequest request) {
        // Handle a new guest (if any):
        String name = request.getParameter("name");
        if (name != null)
            guestDao.persist(new Guest(name));

        // Prepare the result view (guest.jsp):
        return new ModelAndView("guest.jsp", "guestDao", guestDao);
    }
}

The GuestController class is defined as a Spring managed web controller using the @Controller annotation. A GuestDao component is automatically constructed and injected by Spring into the guestDao field (because it is annotated with the @Autowired annotation). The guestbook method, which is attached to the "/guest" web request uri (using the @RequestMapping annotation) uses the GuestDao component to process the web request:

  • If a new guest has registered (using a JSP form that will be added in the next tutorial step) - a new Guest entity object is constructed and stored in the database.
  • Processing is forwarded to a JSP page (which is presented in the next tutorial step) that generates the HTML output. The JSP uses the GuestDao component to display the existing Guest objects. The returned ModelAndView object defines a target JSP ("guest.jsp") and passes the GuestDao component to the JSP as a request attribute (whose name is "guestDao" and its value is guestDao).

The next step is adding a JSP page that will serve as the application view and will produce the guestbook page output.