Thursday, 3 November 2016

Spring MVC

The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet which is like FrontController Servlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files. The default handler is based on the @Controller and @RequestMapping annotations. With Spring 3.0 onwards, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features.

Spring’s web MVC framework is, like many other web MVC frameworks, request-driven, designed around a central Servlet that dispatches requests to controllers and offers other functionality that facilitates the development of web applications.

The request processing work flow of the Spring Web MVC is illustrated in following diagram.


Spring’s view resolution is extremely flexible. A Controller is typically responsible for preparing a model Map with data and selecting a view name but it can also write directly to the response stream and complete the request. View name resolution is highly configurable through file extension or Accept header content type negotiation, through bean names, a properties file, or even a custom ViewResolver implementation. The model (the M in MVC) is a Map interface, which allows for the complete abstraction of the view technology. You can integrate directly with template based rendering technologies such as JSP, Velocity and Freemarker, or directly generate XML, JSON, Atom, and many other types of content. The model Map is simply transformed into an appropriate format, such as JSP request attributes, a Velocity template model.

With this background, let's create basic Spring MVC application. 

In this tutorial, we will be using Spring-webmvc version 4.3.3.RELEASE.

Project Structure at completion of tutorial will be like below,



Create Maven WebApp project using archetype. Once done, update pom.xml as below,

pom.xml
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<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>in.blogspot.ashish4java</groupId>
 <artifactId>SpringMVCExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringMVCExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
  <springframework.version>4.3.3.RELEASE</springframework.version>
 </properties>
 <dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${springframework.version}</version>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
 </dependencies>
 <build>
  <finalName>SpringMVCExample</finalName>
  <pluginManagement>
   <plugins>
    <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-compiler-plugin</artifactId>
     <version>3.6.0</version>
     <configuration>
      <source>1.8</source>
      <target>1.8</target>
     </configuration>
    </plugin>
   </plugins>
  </pluginManagement>
 </build>
</project>

Update web.xml as below,

web.xml
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 version="3.1">
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
  <servlet-name>dispatcherservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/spring/mvc-context.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>dispatcherservlet</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

We have configured DispatcherServlet and passed location of Spring Bean config file as init-param. 

mvc-context.xml
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?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:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

 <mvc:annotation-driven />
 <context:component-scan base-package="in.blogspot.ashish4java.springmvcexample" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>

We have configured this mvc to be annotation driven and also provided base package to scan for annotations.

View Resolver is also configured which will identify view to render response. View will be resolved based on provided prefix and suffix to String returned from Controller method. If Controller method returns String "message" then to render response back, "WEB-INF/jsp/" + "message" + ".jsp" = "WEB-INF/jsp/message.jsp" will be used.

In web.xml, we have configured index.jsp as welcome file.

index.jsp
1
2
3
4
5
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

At this point, if we deploy this app to tomcat server, we should at least get index.jsp page properly. If it doesn't then something is done incorrectly and needs to be further investigated.

Now controller part,
WelcomeController.java
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package in.blogspot.ashish4java.springmvcexample;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class WelcomeController {

 @RequestMapping(path = "/welcome", method = RequestMethod.GET)
 public String sendMessage(ModelMap map) {
  map.addAttribute("message", "Greetings from WelcomeController!");
  return "message";
 }

}

sendMessage method accept GET request coming from url '/welcome' and returning String "message" which as mentioned above will be used to render response. Also ModelMap which implements java.util.Map interface and extends java.util.LinkedHashMap is exposed to web view.

Now last part is to create message.jsp

message.jsp


1
2
3
4
5
6
7
8
<html>
<head>
<title>Spring MVC Example</title>
</head>
<body>
 <h1>Message: ${message}</h1>
</body>
</html>

Once all this done, deploy this application on tomcat server. Once deployed successfully, hit the url http://localhost:8080/SpringMVCExample/ 


then to url http://localhost:8080/SpringMVCExample/welcome to get desired result as below,



No comments:

Post a Comment