This tutorial explains simple Hello World Example for start learning Spring MVC. We have published several tutorials on advanced concepts using spring framework, including spring mvc examples. However, this post is just re-post for the beginners just want to write a bare minimum code for setting up the spring mvc project. If you have any questions on running this example, please write it in the comments section.
Step 1 : Create Dynamic Web Project in Eclipse
Step 2: Import or Copy the required JAR files to the eclipse project or keep it in the class path of your project build. If you are using the maven build, specify the appropriate artifacts in the POM.xml.
Step 3: Create Controller Class
HelloWorldController.java
package javabeat.net; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/helloworld") public class HelloWorldController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute("message", "Hello World Spring MVC Framework!"); return "hello"; } }
Step 4: Create Spring MVC Configuration File HelloWorld-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-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="javabeat.net" /> <bean> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
Step 5: Create Web.xml File
<?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="WebApp_ID" version="2.5"> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Step 6: Create JSP File (View) hello.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html>
Once you have created all the required files, your project structure would look like this:
Add this project to server and run the application. You can access it from the browser.