Spring — MVC Framework
A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-Controller design pattern. It implements all the basic features of a core spring framework like Inversion of Control, Dependency Injection.
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.
- The Model encapsulates the application data and in general they will consist of POJO.
- The View is responsible for rendering the model data and in general it generates HTML output that the client’s browser can interpret.
- The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering.
The DispatcherServlet :
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram −
Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −
After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
- The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
- The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request.
- Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.
All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver are parts of WebApplicationContext w which is an extension of the plainApplicationContext with some extra features necessary for web applications.
The DispatcherServlet
is an actual Servlet
(it inherits from the HttpServlet
base class), and as such is declared in the web.xml
of your web application. You need to map requests that you want the DispatcherServlet
to handle, by using a URL mapping in the same web.xml
file. This is standard Java EE Servlet configuration; the following example shows such a DispatcherServlet
declaration and mapping:
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/example/*</url-pattern>
</servlet-mapping>
</web-app>
Now, let us check the required configuration for spring-servlet.xml file, placed in your web application’s WebContent/WEB-INF directory −
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
Following are the important points about servlet-servlet.xml file −
- The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
- The <context:component-scan…> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc.
- The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp .
The following section will show you how to create your actual components, i.e., Controller, Model, and View.
Spring MVC Using Java Configuration :
To enable Spring MVC support through a Java configuration class, all we have to do is add the @EnableWebMvc annotation:
@EnableWebMvc
@Configuration
public class WebConfig { /// ...
}
This will set up the basic support we need for an MVC project, such as registering controllers and mappings, type converters, validation support, message converters and exception handling.
If we want to customize this configuration, we need to implement the WebMvcConfigurer interface:
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer
{
@Override
public void addViewControllers(ViewControllerRegistry registry)
{
registry.addViewController("/").setViewName("index");
}
@Bean
public ViewResolver viewResolver()
{
InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
Defining a Controller
The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controllerannotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
@Controller
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
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.
Creating JSP Views
Spring MVC supports many types of views for different presentation technologies. These include — JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports, etc. But most commonly we use JSP templates written with JSTL.
Let us write a simple hello view in /WEB-INF/hello/hello.jsp −
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
Here ${message} is the attribute which we have set up inside the Controller. You can have multiple attributes to be displayed inside your view.
Controller and Views
Let’s have a look at an example of a basic controller:
@Controller
public class SampleController {
@GetMapping("/sample")
public String showForm() {
return "sample";
}}
And the corresponding jsp resource is the sample.jsp file:
<html>
<head></head> <body>
<h1>This is the body of the sample view</h1>
</body>
</html>
The JSP based view files are located under the /WEB-INF folder of the project, so they’re only accessible to the Spring infrastructure and not by direct URL access.
Provide project information and configuration in the pom.xml file :
<html>
<head></head><body>
<h1>This is the body of the sample view</h1>
</body>
</html>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name><url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId <version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>
Spring Boot Entry Point :
Each application built using Spring Boot needs merely to define the main entry point. This is usually a Java class with the main method, annotated with @SpringBootApplication:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
This annotation adds the following other annotations:
- @Configuration — which marks the class as a source of bean definitions
- @EnableAutoConfiguration — which tells the framework to add beans based on the dependencies on the classpath automatically
- @ComponentScan — which scans for other configurations and beans in the same package as the Application class or below