AllSpring

Spring MVC 3 Tutorials [ An Introduction ]

So what is Spring MVC ?
Spring MVC is the web component of Spring’s framework apart from Spring WebFlow. Opposed to WebFlow which provides “flow” of the application MVC is more basic and robust implementation of MVC architecture. It provides a rapid development environment by easy integration with spring for enterprise applications. The flexible design of Spring enables Spring MVC to be highly configurable. Read more about Spring MVC here.
[ad#in-blog]
Lets get started with simple MVC project –

Create a new Dynamic Web Project in Eclipse
[I am using STS the fancy Spring Family kin of eclipse, you can get your copy from SpringSource Website]
New Dynamic Web Project
Now update your web.xml file with the below contents –

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="SpringMVCDemo" version="2.5">
	<display-name>SpringMVCDemo</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>
</web-app>

DispatcherServlet is the heart of MVC framework, in the above example we have mapped
all HTML extension pages (*.html) to Spring MVC.
Now next we need to create a configuration file to help Spring MVC handle request for us.
Create a new XML file springMVC-servlet.xml with below contents –

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan
        base-package="com.roadtobe.supaldubey.examples.spring.mvc" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

There are two major things to note here

  • context:component-scan Tag, tells spring the location of the package where it can find controllers, handlers, Service & repository beans[blah, blah ..]. In short this XML tells Spring that “Boss!” you will find my annotated beans here. :-).
  •  viewResolver – This bean is used by Spring MVC to resolve a view. When a Controller method returns ModelAndView, a view resolver is used to map it to an actual JSP page. Here, our sweet viewResolver is letting Spring know that you need to add /WEB-INF/jsp/ as prefix and .jsp as suffix. So if I get hello, viewResolver bean will turn it into /WEB-INF/jsp/hello.jsp

Next step  – Create a folder structure like below –
Project Layout
Add below JARS to your WEB-INF, in case you are unable to find all the Jars,  just chillax, you can download entire project [ Yes! With Jars ] at the end of the post.

@Controller
public class BaseController
{
    @RequestMapping("welcome")
    public ModelAndView welcome(@RequestParam(value = "name", required = false,
	    defaultValue = "Supal Dubey") String name)
    {
	Map model = new HashMap();
	model.put("user", name);
	return new ModelAndView("hello", model);
    }
}

Now here is the fun stuff of Spring MVC. Controller annotation instructs Spring Dispatcher Servlet to register this class as request handler. While RequestMapping tells it which URL pattern will the method handle.
Here welcome method will handle our welcome.html URL request as we have mapped *.html in our web.xml.
RequestParam annotations ask MVC to read the URL params and pass them as Objects to us. Here we have mapped name as parameter with a default value “Supal Dubey”, if I had marked required=true, an Spring MVC will throw an exception in case it was is to find a URL param name.
Similarly we can directly use HTTPServletRequest, HTTPServletResponse, HTTPSession as parameters directly, Spring will inject the params for us. We can also have any data type, Spring will convert it for us. For example, I could have written –

    @RequestMapping("welcome")
    public ModelAndView welcome(@RequestParam(value = "id") Interer id)
    {
	....

Spring will convert id to an Integer for me.
Last but not least. Lets create a JSP for the view –
hello.jsp

<html>
<head>
<title>Supal Dubey! Spring MVC Demo</title>
</head>
<body>
Hello ${user}! Welcome to Spring 3.
</body>
</html>

Now lets just have our index.jsp (default page in web.xml), kick us
to welcome.html, remember we had marked *.html as the URL pattern to be handled by
our Spring MVC dispatcher servlet ? 🙂
You can use any method you like to redirect using request.sendRedirect or by using JSTL redirect. I leave that to you.
Now just run your Dynamic Web project on your server and “Taa Da” ..
Spring MVC Demo, snapshotThat’s it. Thats the beauty of Spring MVC, it leaves no trace of Spring or any MVC related Tags on to your JSP pages. Though you can have Spring <form tags, but I like to have JSP pages with JSTL, makes your code more clean and plug-able.
You can download all this code / project from here for free 😀
If you face any issues or have any question / suggestions,  just leave a comment.

6 thoughts on “Spring MVC 3 Tutorials [ An Introduction ]

  1. buenos dias acabo de enterarme de tu pagina web y la verdad es que me parece super bueno no sabia de mas personas interesadas en estos temas, aqui tienes un nuevo lector que seguira visitandote a diario.

  2. I don’t even know the way I finished up right here, however I believed this publish was good. I do not know who you’re however certainly you’re going to a famous blogger in the event you are not already. Cheers!

  3. Pingback: Sarah
  4. Great post kim,I am just getting my new blog up and running and I have been thinking about all the things I could write about. You have just increased that list 10 fold with your very clear advice.I owe you a Starbucks coffee for that block post. LOL. Thanks a million.

Leave a Reply

Your email address will not be published. Required fields are marked *