2.8k likes | 4.96k Views
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
E N D
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 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
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
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.
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.
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.
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
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>
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.
Request Life-cycle When a request is sent to the Spring MVC Framework the following sequence of events happen. The DispatcherServletfirst 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.
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
Spring MVC Interfaces (Continued) MultipartResolver Handling of file upload LocaleResolver Default uses HTTP accept header, cookie, or session
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
Go to File -> New -> Dynamic Web Project, to create a web project
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.
Artifacts of this application View Pages: Form.jsp Success.jsp Controller class FormController.java Configuration File Dispatcher-servlet.xml
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>
Success.jsp <html> <head> <title>JSP Page</title> </head> <body> <h1>Hello World! Success Page</h1> <h2>${message}</h2> </body> </html>
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; } }
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); Model Parameter Name View Name Model Parameter
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>
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
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.
Enter the file name as "dispatcher-servlet.xml" and click the Finish button.
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>
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).
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.
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