34
Spring MVC Overview

Spring MVC Overview

  • Upload
    landis

  • View
    70

  • Download
    2

Embed Size (px)

DESCRIPTION

Spring MVC Overview. Topics. What is MVC ? Java MVC Frameworks Spring MVC Architecture A First Spring MVC Application. Introduction. Web applications have become a very important part of any enterprise system - PowerPoint PPT Presentation

Citation preview

Page 1: Spring MVC Overview

Spring MVC Overview

Page 2: Spring MVC Overview

2

Topics

• What is MVC ?

• Java MVC Frameworks

• Spring MVC Architecture

• A First Spring MVC Application

Page 3: Spring MVC Overview

3

Introduction

• Web applications have become a very important part of any enterprise system

• The key requirement for a web framework is to simplify development of the Web Tier as much as possible.

• The Spring web framework naturally uses Inversion of Control (IoC) to set the dependencies in the controllers.

• key components of a Spring based web application:– MVC architecture– Spring MVC – Controllers – Themes and locales

Page 4: Spring MVC Overview

4

What Is MVC?

• The purpose of this pattern is to simplify the implementation of applications that need to act upon user requests and manipulate and display data.

• There are three distinct components of this pattern – Model represents data that the user is expecting to see. In most

cases, the model consists of Java beans.– View is responsible for rendering the model. A view in a text

editor probably displays the text in appropriate formatting; in most cases, a view in a web application generates an HTML output that the client's browser can interpret.

– Controller is a piece of logic that is responsible for processing and acting upon the user requests, building an appropriate model, and passing it to the view for rendering. In case of Java web applications, the controller is in most cases a servlet.

• Two models of MVC – MVC type 1 and MVC type 2

Page 5: Spring MVC Overview

5

MVC type 1 architecture

Page 6: Spring MVC Overview

6

MVC type 1 architecture

• In this type, the JSP pages are in the center of the application.

• They contain both the control logic and presentation logic. • The client makes a request to a JSP page; the logic in the

page then builds (typically plain old Java objects) and renders the model.

• The separation of the presentation layer and control layer is not very clear.

• In fact, with the exception of "Hello world" applications, Model 1 quickly grows out of control, simply because of the amount of logic that different JSP pages need to perform.

Page 7: Spring MVC Overview

7

MVC type 2 architecture

Page 8: Spring MVC Overview

8

MVC type 2 architecture

• Model 2 is far more manageable in a larger application. • Whereas in Model 1, a JSP page was both the view and controller, in

Model 2, there is a separate JSP page for the controller.• It is now the controller that intercepts the user requests, prepares the

model, and passes it to the view for rendering.• The JSP pages no longer contain logic for processing the requests;

they simply display the model prepared by the controller.• We used JSP in place of the view and controller in Model 1 and the

view in Model 2. • This is obviously incorrect because the view is not limited to just JSP

pages. • Spring MVC architecture is an implementation of Model 2 MVC,

hence the view can be anything that can render the model and return it to the client.

Page 9: Spring MVC Overview

9

Spring MVC

• Spring MVC support allows us to build flexible applications using an MVC Model 2 pattern.

• The implementation is truly generic, the model is a simple Map that holds the data, View is an interface whose implementations render the data, and the controller is an implementation of the Controller interface

• Spring's implementation of the MVC architecture for web applications is based around DispatcherServlet

• This servlet processes the requests and invokes appropriate controllers to handle the request.

Page 10: Spring MVC Overview

DispatcherServlet

• The DispatcherServlet is the Front Controller

• Coordinates the request life-cycle

• Loads Spring application context from XML configuration file

– /WEB-INF/[servlet-name]-servlet.xml

• Initializes WebApplicationContext– WebApplicationContext is bound into ServletContext

• Configured in web.xml

Page 11: Spring MVC Overview

Configuration of DispatcherServlet in web.xml

<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>*.form</url-pattern>

</servlet-mapping>

</web-app>

Page 12: Spring MVC Overview

12

DispatcherServlet

• The DispatcherServlet intercepts the incoming requests and determines which Controller will handle the request.

• The Spring controllers return a ModelAndView class from their handling methods.

• The ModelAndView instance holds a reference to a view and a model.

• The model is a simple Map instance that holds Java beans that the view is going to render.

• The View is an interface that, when implemented, defines the render method. It makes sense that the View implementation can be virtually anything the client can interpret.

Page 13: Spring MVC Overview

13

Request Life-cycle

Page 14: Spring MVC Overview

14

Request Life-cycle

When a request is sent to the Spring MVC Framework the following sequence of events happen.

• The DispatcherServlet first receives the request.

• The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.

• The Controller process the request by calling the appropriate service methods and returns a ModeAndView object to the DispatcherServlet.

• The ModeAndView object contains the model data and the view name.

• The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.

• Now the DispatcherServlet will pass the model object to the View to render the result.

• The View with the help of the model data will render the result back to the user.

Page 15: Spring MVC Overview

Spring MVC Interfaces

• HandlerMapping– Routing of requests to handlers (controllers)

• HandlerAdapter– Adapts to handler interface – Default utilizes Controllers

• HandlerExceptionResolver– Maps exceptions to error pages– Similar to standard Servlet, but more flexible

• ViewResolver– Maps symbolic name to view

Page 16: Spring MVC Overview

Spring MVC Interfaces (Continued)

• MultipartResolver– Handling of file upload

• LocaleResolver– Default uses HTTP accept header, cookie, or

session

Page 17: Spring MVC Overview

22

Spring MVC - Hello world example

• To understand the Spring MVC Framework we will now create a simple hello world example using the Eclipse IDE.

• Tools used:– Exclipse IDE 3.4

– Spring IDE plugin,

– Tomcat 6.0

– Spring 3.0

Page 18: Spring MVC Overview

23

Go to File -> New -> Dynamic Web Project, to create a web project

Page 19: Spring MVC Overview

24

Enter the project name and click the Finish button

Page 20: Spring MVC Overview

25

Add Spring Project Nature

Right click the project folder, and select Spring Tools -> Add Spring Project Nature, to add Spring capabilities to the web project. This feature will be available once you install the Spring IDE.

Page 21: Spring MVC Overview

26

Application

Page 22: Spring MVC Overview

27

Artifacts of this application

• View Pages:– Form.jsp

– Success.jsp

• Controller class– FormController.java

• Configuration File– Dispatcher-servlet.xml

Page 23: Spring MVC Overview

28

Form.jsp

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1>Hello World!</h1>

<a href="success.do">click here</a>

</body>

</html>

Page 24: Spring MVC Overview

29

Success.jsp

<html> <head> <title>JSP Page</title> </head> <body> <h1>Hello World! Success Page</h1> <h2>${message}</h2> </body></html>

Page 25: Spring MVC Overview

30

Spring controller class - FormController.java

package com.company.controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.Controller;

public class FormController implements Controller {

private String msg;

public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {

return new ModelAndView("success","message", msg);

}

public void setMsg(String msg) {

this.msg = msg;

}

}

Page 26: Spring MVC Overview

31

Spring controller class - FormController.java

• The FormController class has a msg property that is set thru the setter injection. The FormController class should override the handleRequest() method to process the request.

• After processing the request the handleRequest() method returns a ModelAndView object back to the DispatcherServlet.

return new ModelAndView("success","message", msg);

View Name

Model Parameter

Model ParameterName

Page 27: Spring MVC Overview

32

Configuration of DispatcherSevlet in web.xml

<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet

</servlet-class></servlet>

<servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>

Page 28: Spring MVC Overview

33

Spring MVC configuration file

• Here the servlet name is dispatcher.

• By default the DispatcherServlet will look for a file name dispatcher-servlet.xml to load the Spring MVC configuration.

• This file name is formed by concatenating the servlet name ("dispatcher") with "-servlet.xml".

• Here we user the the url-pattern as ".do" in order to hide the implementations technology to the users

Page 29: Spring MVC Overview

34

To create a bean configuration file right click the WebContent folder and select New -> Other. The following dialog box appears

Select the Spring Bean Configuration

file and click Next.

Page 30: Spring MVC Overview

35

Enter the file name as "dispatcher-servlet.xml" and click the Finish button.

Page 31: Spring MVC Overview

36

Configure the Controller and the ViewResolver classes in bean file

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver"

p:prefix="/WEB-INF/jsp/"

p:suffix=".jsp" />

<bean name="/success.do" class="com.company.controller.FormController">

<property name="msg" value="Welcome from Spring MVC Team"/>

</bean>

Page 32: Spring MVC Overview

37

Understand how to configure the controller

<bean name="/success.do" class="com.sqlstar.controller.FormController">

<property name="msg" value="Welcome from SQLSTAR"/>

</bean>

• Here the name attribute of the bean element indicates the URL pattern to map the request. Since the id attribute can't contain special characters like "/" , we specify the URL pattern using the name attribute of the bean element. By default the DispatcherServlet uses the BeanNameUrlHandlerMapping to map the incoming request. The BeanNameUrlHandlerMapping uses the bean name as the URL pattern. Since BeanNameUrlHandlerMapping is used by default, you need not do any seperate configuration for this.

• We set the msg attribute of the FormController class thru setter injection. The FormController class is configured just like an another JavaBean class in the Spring application context, so like any other JavaBean we can set values to it through Dependency Injection(DI).

Page 33: Spring MVC Overview

38

ViewResolver

• The form.jsp will redirect the request to the DispatcherServlet, which inturn consults with the BeanNameUrlHandlerMapping and invokes the FormController. The handleRequest() method in the FormController class will be invoked.

• Here we return the msg property under the name “message” and the view name “success” to the DispatcherServlet.

• As of now we only know the view name, and to find the actual view to invoke we need a ViewResolver.

Page 34: Spring MVC Overview

39

The ViewResolver is configured using the following code

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

• Here the InternalResourceViewResolver is used to resolve the view name to the actual view. The prefix value + view name + suffix value will give the actual view location.

• Here the actual view location is /WEB-INF/jsp/success.jsp