Author |
Topic: Spring MVC -- A Web Development Framework |
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Spring MVC -- A Web Development Framework |
Introduction
The Spring Model-View-Controller (MVC) framework is designed around the DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for uploading files. The default handler is based on the @Controller and @RequestMapping annotations, offering a wide range of flexible handling methods. With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features.
Prerequsites
Eclipse with Spring Tools Suite (STS) -- link Dependencies (pom.xml):
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
</dependencies>
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Why Spring MVC |
Following are some of the distinct advantages of Spring MVC architecture
MVC is a common design pattern used to decouple business logic from UIs to allow them to change independently without affecting each other. Convention over configuration -- Similar to Ruby on Rails or other popular web frameworks
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Spring MVC -- Flow |
+-----------+
| View | /WEB-INF/views/
+-----------+ +-----------+
| Filters | |
+-----------+ |
| |
| +------------+ +-----------+
client ----> DispatcherServlet ---> | Controller |------------| Model | /app/models/
+------------+ +-----------+
/WEB-INF/web.xml @Controller |
@RequestMapping |
------
| DB |
------
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Spring MVC -- Configuration |
/WEB-INF/web.xml
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/*.xml</param-value>
</context-param>
<!-- LISTENERS -->
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- FILTERS -->
<!-- Creates the filters shared by all Servlets and Filters -->
<!-- ... -->
<!-- SERVLETS -->
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/myServlet/dispatch-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
dispatch-servlet.xml
<!-- Resolves views selected for rendering by @Controller -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- bean injection by constructor
<constructor-arg></constructor-arg>
-->
<!-- bean injection by setter -->
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Auto-detection for annotation @Controllers -->
<context:component-scan base-package="com.xyz.springmvc" />
<context:component-scan base-package="com.xyz.springmvc2" />
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
MVC -- Controller |
@Controller
public class HomeController {
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String home(Locale locale, Model model)
{
String server_timestamp = new Date().toString();
model.addAttribute("serverTime", server_timestamp);
return "home";
}
}
With the above code, the Spring Framework can do following jobs: @Controller -- The class HomeController has been annotated as a controller @RequestMapping(value = "/index", method = RequestMethod.GET) -- The HTTP GET request http://<host>:<port>/<context>/index will be served by the annotated method home(Locale locale, Model model) Locale locale, Model model -- Dependencies will be injected silently under the hood by Spring Framework return "home" -- The view will be rendered by "<prefix>home<suffix>" with the help of dispatch-servlet.xml
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
MVC -- View |
home.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello world!</h1>
<P>The time on the server is ${serverTime}.</P>
</body>
</html>
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
MVC -- Model |
Controller method's arguments: Request or response objects: ServletRequest, HttpServletRequest Session object: HttpSession org.springframework.web.context.request.WebRequest java.util.Locale java.io.InputStream / java.io.Reader java.io.OutputStream / java.io.Writer java.security.Principal @PathVariable annotated parameters for access to URI template variables @RequestParam annotated parameters for access to specific Servlet request parameters @RequestHeader annotated parameters for access to specific Servlet request HTTP headers @RequestBody annotated parameters for access to the HTTP request body java.util.Map / org.springframework.ui.Model / org.springframework.ui.ModelMap org.springframework.validation.Errors / org.springframework.validation.BindingResult validation results for a preceding command org.springframework.web.bind.support.SessionStatus status handle for marking form processing as complete, which triggers the cleanup of session attributes that have been indicated by the @SessionAttributes annotation at the handler type level.
Controller method's return types: ModelAndView, Model, Map, View String void -- if the method handles the response itself (by writing the response content directly, declaring an argument of type ServletResponse / HttpServletResponse for that purpose) or if the view name is supposed to be implicitly determined through a RequestToViewNameTranslator (not declaring a response argument in the handler method signature). HttpEntity<?> or ResponseEntity<?> -- to provide access to the Servlet reponse HTTP headers and contents Any other return type is considered to be a single model attribute to be exposed to the view, using the attribute name specified through @ModelAttribute at the method level
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Eclipse IDE Example |
Prerequisites STS 3.0 Tomcat 8.5
On Eclipse IDE File > New > Project ... > Spring > Spring Legacy Project > Next Type in Project Name: HelloWorldSpringMVC Select Templates > Spring MVC Project Specify the package name: com.example.myapp
Note: myapp will be web context name -- http://localhost:8080/myapp/
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Project's Structure |
[+] ... HelloWorldSpringMVC
[+] ... src
[+] ... main
[+] ... java
[+] ... com
[+] ... example
[+] ... myapp
[-] ... HomeController.java
[+] ... resources
[-] ... log4j.xml
[+] ... webapp
[+] ... resources
[+] ... WEB-INF
[+] ... classes
[+] ... spring
[+] ... appServlet
[-] ... servlet-context.xml
[-] ... root-context.xml
[+] ... views
[-] ... home.jsp
[+] ... web.xml
[+] ... test
[+] ... target
[-] ... pom.xml
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
web.xml |
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
servlet-context.xml |
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.example.myapp" />
</beans:beans>
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
HomeController.java |
package com.example.myapp;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
}
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Run it |
http://localhost:8080/myapp/
Hello world!
The time on the server is October 7, 2019 12:12:12 AM EST.
|
|
|
|
|
|
|