Spring MVC FrameWork
Spring MVC framework is a robust Model view controller framework that helps us to develop a loosely coupled web application. It separates different aspects of web applications with the help of MVC architecture.
The Spring Web MVC framework provides Model-View-Controller (MVC) architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic) while providing a loose coupling between these elements.
Model: Model carries application data. It generally includes POJO in the form of business objects
View: View is used to render the User interface (UI). It will render application data on UI. For example JSP
Controller: Controller takes care of processing user request and calling back end services.
Spring MVC workflow
Spring MVC tutorial
In this post, we will learn about Spring MVC tutorial.
Spring MVC framework is a robust Model view controller framework which helps us to develop a loosely coupled web application. It separates different aspects of web applications with the help of MVC architecture.
Model: Model carries application data. It generally includes POJO in the form of business objects
View: View is used to render User interface (UI). It will render application data on UI. For example JSP
Controller: Controller takes care of processing user request and calling back end services.
This Spring MVC tutorial is made for beginners as well as for experienced programmers.
Spring MVC workflow
The following steps are involved in the Spring MVC workflow.
- The request will be received by Front Controller i.e. DispatcherServlet.
- DispatcherServlet will pass this request to HandlerMapping. HandlerMapping will find a suitable Controller for the request
- HandlerMapping will send the details of the controller to DispatcherServlet.
- DispatcherServlet will call the Controller identified by HandlerMapping. The Controller will process the request by calling an appropriate method and prepare the data. It may call some business logic or directly retrieve data from the database.
- The Controller will send ModelAndView(Model data and view name) to DispatcherServlet.
- Once DispatcherServlet receives ModelAndView object, it will pass it to ViewResolver to find appropriate View.
- ViewResolver will identify the view and send it back to DispatcherServlet.
- DispatcherServlet will call the appropriate View identified by ViewResolver.
- The View will create Response in form of HTML and send it to DispatcherServlet.
- DispatcherServlet will send the response to the browser. The browser will render the HTML code and display it to the end-user.
The below diagram will make it clearer.
I hope you will have a good understanding of How Spring MVC handles the request and send the response back.
I have written some good annotations for the Spring MVC. Let me list them down here.
Spring MVC basics
Spring Component, Service, Repository, and Controller
There is three most important annotation in Spring i.e. @Component, @Service, and @Repository. These annotations are used to declare appropriate beans based on their nature.
Spring MVC @RequestMapping
Spring MVC @RequestMapping provides details about an important Spring MVC annotation called @RequestMapping.@RequestMapping annotation is used to map incoming requests to the appropriate method of the controller class.
Spring MVC @RestController annotation
Spring MVC @RestController annotation is used to declare Controller in Spring MVC. It was introduced in Spring 4. When you use @RestController, you don’t need to define @ResponseBody.
Spring MVC @ModelAttribute annotation
Spring MVC @ModelAttribute is used to bind request parameters to model objects.
Implementing Controllers
Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.
Spring 2.5 introduced an annotation-based programming model for MVC controllers that uses annotations such as @RequestMapping
, @RequestParam
, @ModelAttribute
, and so on. This annotation support is available for both Servlet MVC and Portlet MVC. Controllers implemented in this style do not have to extend specific base classes or implement specific interfaces. Furthermore, they do not usually have direct dependencies on Servlet or Portlet APIs, although you can easily configure access to Servlet or Portlet facilities.
@Controller
public class HelloWorldController {
@RequestMapping("/helloWorld")
public String helloWorld(Model model) {
model.addAttribute("message", "Hello World!");
return "helloWorld";
}
}
As you can see, the @Controller
and @RequestMapping
annotations allow flexible method names and signatures. In this particular example the method accepts a Model
and returns a view name as a String
, but various other method parameters and return values can be used as explained later in this section. @Controller
and @RequestMapping
and a number of other annotations form the basis for the Spring MVC implementation. This section documents these annotations and how they are most commonly used in a Servlet environment.
Defining a controller with @Controller
The @Controller
annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API. However, you can still reference Servlet-specific features if you need to.
The @Controller
annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping
annotations (see the next section).
You can define annotated controller beans explicitly, using a standard Spring bean definition in the dispatcher's context. However, the @Controller
stereotype also allows for autodetection, aligned with Spring general support for detecting component classes in the classpath and auto-registering bean definitions for them.
To enable autodetection of such annotated controllers, you add component scanning to your configuration. Use the spring-context schema as shown in the following XML snippet:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>
<!-- ... -->
</beans>
Mapping Requests With @RequestMapping
You use the @RequestMapping
annotation to map URLs such as /appointments
onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping for a specific HTTP method request method ("GET", "POST", etc.) or an HTTP request parameter condition.
The following example from the Petcare sample shows a controller in a Spring MVC application that uses this annotation:
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
@Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
@RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
@RequestMapping(value="/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}
@RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
}
@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}
In the example, the @RequestMapping is used in a number of places. The first usage is on the type (class) level, which indicates that all handling methods on this controller are relative to the /appointments path. The get() method has a further @RequestMapping refinement: it only accepts GET requests, meaning that an HTTP GET for /appointments invokes this method. The post() has a similar refinement, and the getNewForm() combines the definition of HTTP method and path into one, so that GET requests for appointments/new are handled by that method.
The getForDay()
method shows another usage of @RequestMapping
: URI templates. (See the next section ).
A @RequestMapping
on the class level is not required. Without it, all paths are simply absolute, and not relative. The following example from the PetClinic sample application shows a multi-action controller using @RequestMapping
:
@Controller
public class ClinicController {
private final Clinic clinic;
@Autowired
public ClinicController(Clinic clinic) {
this.clinic = clinic;
}
@RequestMapping("/")
public void welcomeHandler() {
}
@RequestMapping("/vets")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
}
New Support Classes for @RequestMapping methods in Spring MVC 3.1
Spring 3.1 introduced a new set of support classes for @RequestMapping
methods called RequestMappingHandlerMapping
and RequestMappingHandlerAdapter
respectively. They are recommended for use and even required to take advantage of new features in Spring MVC 3.1 and going forward. The new support classes are enabled by default by the MVC namespace and the MVC Java config but must be configured explicitly if using neither. This section describes a few important differences between the old and the new support classes.
Prior to Spring 3.1, type and method-level request mappings were examined in two separate stages -- a controller was selected first by the DefaultAnnotationHandlerMapping
and the actual method to invoke was narrowed down second by the AnnotationMethodHandlerAdapter
.
With the new support classes in Spring 3.1, RequestMappingHandlerMapping
is the only place where a decision is made about which method should process the request. Think of controller methods as a collection of unique endpoints with mappings for each method derived from type and method-level @RequestMapping
information.
This enables some new possibilities. For once HandlerInterceptor
or a HandlerExceptionResolver
can now expect the Object-based handler to be a, which allows them to examine the exact method, its parameters, and associated annotations. The processing for a URL no longer needs to be split across different controllers.
There are also several things no longer possible:
- Select a controller first with a
SimpleUrlHandlerMapping
orBeanNameUrlHandlerMapping
and then narrow the method based on@RequestMapping
annotations. - Rely on method names as a fall-back mechanism to disambiguate between two
@RequestMapping
methods that don't have an explicit path mapping URL path but otherwise match equally, e.g. by HTTP method. In the new support classes@RequestMapping
methods have to be mapped uniquely. - Have a single default method (without an explicit path mapping) with which requests are processed if no other controller method matches more concretely. In the new support classes if a matching method is not found a 404 error is raised.
The above features are still supported by the existing support classes. However, to take advantage of the new Spring MVC 3.1 features you'll need to use the new support classes.