Tuesday, August 3, 2010

Spring MVC Tutorial

Spring framework is very wide subject. Here, I have shared whatever I know. I don’t like to read very lengthy topic, so I have tried to explain the things as concise as possible. My aim here is to explain how you can develop basic Spring MVC application. It will be mostly helpful to the beginners.

I will write new posts explaining different things around Spring as time permits. Any comments and suggestions are heartily accepted.

Jars:-
spring-2.0.6.jar, commons-logging-1.1.jar, jstl.jar, standard.jar

Environment:-
Eclipse3.4.2, Tomcat6.0, jdk1.6.0_11

Sequence of procedure of handling request in Spring MVC:-
1) Any request first goes to DispatcherServlet, which is configured in web.xml.
2) DispatcherServlet consults HandlerMapping, which is configured in xml Configuration file and invokes theController associated with the request.
3) Controller processes the request by applying appropriate Model’s service methods and returns a ModelAndViewobject to the DispatcherServlet, which contains model data and logical view name.
4) DispatcherServlet consults ViewResolver to find the actual View using logical view and pass the model object to the View to render the result to User.

1. Configuration in web.xml

First configure DispatcherServlet to web.xml like below.

“1.0″ encoding=“UTF-8″?>

“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 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”version=“2.5″>

Sample_Spring_Prj

/jsp/homePage.jsp

dispatcher

org.springframework.web.servlet.DispatcherServlet

1

dispatcher

*.html

By default, DispatcherServlet looks for a configuration file named [servlet-name]-servlet.xml (here, dispatcher-servlet.xml) in the WEB-INF directory of your web application.

1.1 Splitting Configuration file

Generally, a web application has many controllers performing different task. It is not good idea to put all controllers under one configuration file. Splitting configuration file can make maintenance easier. To ensure that all of these configuration files are loaded, you’ll need to configure a context loader in your web.xml.

org.springframework.web.context.ContextLoaderListener

contextConfigLocation

/WEB-INF/configurationFile1.xml

/WEB-INF/ configurationFile2.xml

A context loader loads context configuration files in addition to the one that DispatcherServlet loads. The most commonly used context loader is a servlet listener called ContextLoaderListener. With it you need to specify location of configuration file by setting contextConfigLocation parameter in the servlet context. If not specified, the context loader will look for a Spring configuration file at /WEB-INF/ applicationContext.xml.

Note:- Some older web containers do not initialize servlet listener before servlets. You will have to use ContextLoaderServlet instead of ContextLoaderListener.

2. XML Configuration file

File name is dispatcher-servlet.xml.

“1.0″ encoding=“UTF-8″?>

“http://www.springframework.org/schema/beans” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=“http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd”>

“urlMapping” class=“org.springframework.web.servlet.handler.SimpleUrlHandlerMapping”>

“mappings”>

“/resultPage.html”>loginController

“loginController” class=“com.LoginController” />

DispatcherServlet looks here for some controller bean associated with specific request url. By default, this is done by a BeanNameUrlHandlerMapping which looks for a bean that has the same name as url. Ex: “/resultPage.html “class=“com.LoginController” />. In this case, you have to provide bean name because name contains request url which contains special character like ‘/’ which is not allowed in id.

If you want bean name different than url name or in specific manner then you can use SimpleUrlHandlerMapping. The value of each is the bean name of a controller that will handle requests to the url pattern. In above example, request url is …/ resultPage.html, so LoginController class will be executed. In this case, you can use name or id anything.

In this example, request comes from homePage.jsp like below.

<%@ page contentType=“text/html;charset=UTF-8″ language=“java” %>

Sample Spring Application

“resultPage.html”>

User Name “username” type=“text” />

Password “password” type=“password” />

“submit” type=“submit” value=“Submit” />

3. Controller Class

public class LoginController extends AbstractController {

public LoginController(){

}

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

ModelAndView mv = new ModelAndView(); //default constructor is available in spring version 2.0 and later

mv.addObject(“resultMsg”, “Successfully Login”);

mv.setViewName(“resultPage”);

return mv;

/* For older version of spring, instead of all above lines you can write:

return new ModelAndView(“resultPage”,”resultMsg”, “Successfully Login”);

*/

}

}

When program control comes here, it will execute handleRequestInternal method, so write controller logic in this method. Here, you can use other beans and Model’s service method to process request and get result data. Now, Controller will set result data to ModelAndView object to be used by View for rendering purpose and will set logical view name. The controller completes it work by returning the created ModelAndView object that DispatcherServlet will use to select a view from viewResolver.

4. View Resolver from XML Configuration file

Write below code in above Configuration file dispatcher-servlet.xml.

“viewResolver” class=“org.springframework.web.servlet.view.InternalResourceViewResolver” >

“prefix” value=“/jsp/” />

“suffix” value=“.jsp” />

InternalResourceViewResolver is used to get actual view from logical view name. It makes actual view like prefix-value + logical view name + suffix-value (here, /jsp/ resultPage.jsp) and control is passed to jsp page, in this case.

5. View/ JSP

Here, directly you can access object value with its name which you set to ModelAndView object.

<%@ page contentType=“text/html;charset=UTF-8″ language=“java” %>

<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>

Login Confirmation

Source Code Download. It does not contain jars.

Jars used in this project Download.

No comments:

Post a Comment