Creating the Spring MVC Controller

We will now create the Controller class. In Spring MVC, the Controller is mapped to the request URL and handles requests matching the URL pattern. The request URL for matching an incoming request is specified at the method level in the controller. However, more generic request mapping can be specified at the Controller class level, and a specific URL, with respect to the URL at the class level, can be specified at the method level.

Create a class named CourseController in the packt.jee.course_management.controller package. Annotate it with @Controller. The @Controller annotation is of type @Component, and allows the Spring Framework to identify that class specifically as a controller. Add the method to get courses in CourseController:

@Controller 
public class CourseController { 
  @Autowired 
  CourseDAO courseDAO; 
 
  @RequestMapping("/courses") 
  public String getCourses (Model model) { 
    model.addAttribute("courses", courseDAO.getCourses()); 
    return "courses"; 
  } 
} 

The CourseDAO instance is autowired; that is, it will be injected by Spring. We have added the  getCourses method, which takes a Spring Model object. Data can be shared between View and Controller using this Model object. Therefore, we add an attribute to Model, named courses, and assign the list of courses that we get by calling courseDAO.getCourses. This list could be used in the View JSP as the courses variable. We have annotated this method with @RequestMapping. This annotation maps the incoming request URL to a controller method. In this case, we are saying that any request (relative to the root) that starts with /courses should be handled by the getCourses method in this controller. We will add more methods to CourseController later and discuss some of the parameters that we can pass to the @RequestMapping annotation, but first let's create a View to display the list of courses.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.239.166