Module 14: Spring MVC Introduction - dineshmadhup/Spring GitHub Wiki

This description is based on Module-14 code.

The Spring Web model-view-controller (MVC) framework is designed around a 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.

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 J2EE servlet configuration; the following example shows such a DispatcherServlet declaration and mapping.

Lets define and configure each of these using Eclipse IDE and write some code.

Spring MVC Configuration

The configuration files will be inside the directory: WEB-INF/web.xml

web.xml

<display-name>spring-mvc-demo</display-name>

<!-- Spring MVC Configs -->

<!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
<servlet>
	<servlet-name>dispatcher</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

   <!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
<servlet-mapping>
	<servlet-name>dispatcher</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

There are 5 steps (2 in web.xml and 3 in abc...servlet.xml) to configure spring MVC:

1. Configure Spring MVC Dispatcher Servlet:

    <!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
<servlet>
	<servlet-name>dispatcher</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

2. Set up URL mapping to spring MVC Dispatcher Servlet

    <!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
      <servlet-mapping>
     <servlet-name>dispatcher</servlet-name>
     <url-pattern>/</url-pattern>
    </servlet-mapping>

Upon initialization of a DispatcherServlet, the framework looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.

spring-mvc-demo-servlet.xml

<context:component-scan base-package="com.mycode.springdemo" />

<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>

<!-- Step 5: Define Spring MVC view resolver -->
<bean		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/view/" />
	<property name="suffix" value=".jsp" />
</bean>

Add configurations to file: WEB-INF/spring-mvc-demo-servlet.xml

3. Add support for spring component scanning:

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:

<context:component-scan base-package="com.mycode.springdemo" />

4. Add support for conversion, formatting and validation

mvc:annotation-driven/

5. Configure Spring MVC view resolver

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

More about view resolver configurations:

When app provided a “view” name Spring MVC will -prepend the prefix -append the suffix

Developing Spring Controllers and Views

Development Steps: 1. Create a controller class 2. Define Controller method 3. Add Request Mapping to Controller method 4. Return view page 5. Create view page

1. Create Controller class

  @Controller
  public class HomeController {
   ....
   ....
  }

Defining 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.

Note: @Controller inherits from @Component ... supports scanning

2. Defining Controller method:

public String showPage() { return "main-menu"; }

3. Add Request Mapping to Controller method:

    @RequestMapping("/")
public String showPage() {
	return "main-menu";
}

Defining Mapping Request 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") or specific HTTP request parameters.

4. Return view page

  @RequestMapping("/")
  public String showPage() {
       return "main-menu"; ==> main-menu is view page
  }

5. Create view page

main-menu.jsp

<!DOCTYPE html>

<body>

<div class="container">

<h2>Spring MVC Demo - Home Page</h2>

</div>

</body>

Example:

HomeController.java

@Controller public class HomeController {

@RequestMapping("/")
public String showPage() {
	return "main-menu";
}

}

References:

  1. Spring Framework Reference Documentation: http://docs.spring.io/spring-framework/docs/3.0.x/reference/mvc.html

  2. Luv2Code: http://www.luv2code.com

⚠️ **GitHub.com Fallback** ⚠️