eclipse maven spring MVC project

Eclipse maven spring mvc hello world:

Eclipse provides m2eclipse plugin to integrate Maven and Eclipse together.

Steps to create maven java web project in eclipse:

  1. In eclipse, click on File menu → New → Maven Project. Select maven-archetype-webapp template to create java project and Click on Next button.
  2. Now provide the group Id, artifact Id and Package. Click on Finish button. Complete directory structure and all files like web.xml file, pom.xml file, test case file etc will be created automatically.

Example:



Hello World!

Edit Auto created web.xml:




   Archetype Created Web Application
  
        
		dispatcher
		
			org.springframework.web.servlet.DispatcherServlet
		
		1
	
 
	
		dispatcher
		/
	
 
	
		contextConfigLocation
		/WEB-INF/dispatcher-servlet.xml
	
 
	
		
			org.springframework.web.context.ContextLoaderListener
		
	

Add dependencies in auto created pom.xml:


  4.0.0
  tutorialspointexamples
  SpringMVCHelloWorld
  war
  0.0.1-SNAPSHOT
  SpringMVCHelloWorld Maven Webapp
  http://maven.apache.org
  
      
        junit
        junit
        3.8.1
        test
      

      
      
		org.springframework
		spring-core
		${spring.version}
	
	
	
		org.springframework
		spring-web
		${spring.version}
	
	
	
		org.springframework
		spring-webmvc
		${spring.version}
	
  
  
    SpringMVCHelloWorld
  

Create an xml file dispatcher-servlet.xml file under the /WEB-INF/ directory.




        
       

	
		
			/WEB-INF/views/
		
		
			.jsp
		
	

Here prefix property specifies the directory of jsp files (view files). The suffix property specifies the file extension of view files.

Create Spring Controller

Create the HelloWorldController (HelloWorldController.java) under src/main/java/ directory:

package com.w3schools360.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
	String message = "Hello ";

	@RequestMapping("/hello")
	public ModelAndView showMessage(
			@RequestParam(value = "name", required = false, 
			defaultValue = "World") String name) {

		ModelAndView mv = new ModelAndView("helloWorld");
		mv.addObject("message", message);
		mv.addObject("name", name);
		return mv;
	}
}

The @RequestMapping annotation maps web requests to specific handler classes or handler methods.
The @RequestParam annotation is used for method parameter which should be bound to a web request parameter.
The new ModelAndView(“helloWorld”) refers to the target view.