First Time Spring MVC

Very first time with Spring MVC? This will help!

Objective

  • How to build web application using Spring MVC?

Environment

  • Eclipse (Indigo) or any other version
  • Jetty (eclipse-plugin) or any other server

Libraries

( 1 ) Create Java Project

create java project with the following directory structure, copy jar files to “lib” folder

 

( 2 ) Java Classes

MyController.java

package com.hmkcode.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {

	@RequestMapping("/hello")
	public String sayHello(){
		System.out.println("hello");
		//return redirect us to (view) index.html 
		return "/index.html";
	}

}

( 3 ) web.xml

<?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" version="2.5">

	<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>/rest/*</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

( 4 ) Spring XML Configuration (springmvc-servlet.xml)

Note: file name should be [servlet name]-servlet.xml where servlet name is the name defined in web.xml

<?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: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.xsd">

	<context:component-scan base-package="com.hmkcode.controllers" />

</beans>

( 5 ) Deploy and Run

  • you should see “hello” printed on the console.
  • The “Hello!” message on the browsers is static because we have been redirected to index.html