This tutorial shows steps for creating Spring MVC Project in Eclipse Using Maven. As you know that Maven and Eclipse are using widely in java programming. The example will show step by step with the illustrated pictures.
Table of contents:
1. Create a Maven Project
2. Maven dependencies
3. Configure Spring MVC with Java Annotation Configuration
4. Configure the Dispatcher Servlet
5. Create the Controller
6. Create the View
7. Deploy Spring MVC Project in Eclipse Using Maven
Other interesting posts you may like
Now, we are ready to follow the step by step for creating Spring MVC Project in Eclipse Using Maven like below:
Create a Maven Project
Create a Maven project on Eclipse by following the below steps:
1. On Eclipse IDE, open the following popup by choosing the path File -> New -> Other
2. Select workspace
3. Select webapp
4. Specify Archetype parameters that includes Group Id and Artifact Id
GroupId identifies the project uniquely across all projects, so we need to enforce a naming schema. ArtifactId is the name of the jar without version.
Click button Finish, the Maven project is created, in the Eclipse Navigator the project should look like the following:
Maven dependencies
Currently, We have only the skeleton of maven project. We have to add Spring library and other necessary library. The dependencies should be added in the pom.xml like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode</groupId> <artifactId>springmvc</artifactId> <version>1.0.0</version> <name>SPRING-MVC - ${project.artifactId}</name> <url>http://javabycode.com</url> <packaging>war</packaging> <properties> <springframework.version>4.3.0.RELEASE</springframework.version> </properties> <dependencies> <!-- Spring dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <!-- Servlet dependencies --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>spring-mvc-maven</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>spring-mvc-maven</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> |
Configure Spring MVC with Java Annotation Configuration
Here, we create WebMvcConfigurerAdapter by using Java Annotation configuration. It replaces for the web.xml file.
You can study deeply about the WebMvcConfigurerAdapter class by refering to the post Spring MVC Annotation Example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.javabycode.config; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.javabycode") public class MyWebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/static/"); } } |
Configure the Dispatcher Servlet
The DispatcherServlet is used to dispatch the requests to the appropriate controller methods. We configure it by extending the AbstractAnnotationConfigDispatcherServletInitializer. This class replaces for the normal spring configuration file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.javabycode.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class ServletInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(MyWebConfig.class); ctx.setServletContext(container); ServletRegistration.Dynamic servlet = container.addServlet( "dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); } } |
Create the Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
package com.javabycode.springmvc; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.javabycode.model.Employee; @Controller @RequestMapping("/") public class MyController { /* * This method will serve as default GET handler. */ @RequestMapping(method = RequestMethod.GET) public String newProfile(ModelMap model) { Employee employee = new Employee(); model.addAttribute("employee", employee); return "employee"; } /* * This method will be called on form submission, handling POST request It * also validates the user input */ @RequestMapping(method = RequestMethod.POST) public String saveProfile(Employee employee, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "employee"; } model.addAttribute("success", "Dear " + employee.getFirstName() + " , your profile completed successfully"); model.addAttribute("employee",employee); return "success"; } /* * Method used to populate the country list in view. Note that here you can * call external systems to provide real data. */ @ModelAttribute("countries") public List<String> initializeCountries() { List<String> countries = new ArrayList<String>(); countries.add("USA"); countries.add("Canada"); countries.add("France"); countries.add("Indonesia"); countries.add("Australia"); countries.add("Other"); return countries; } } |
Create the View
Finally, we create a form view and another view that displays form data. The form view looks like the following:
employee.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Profile Employee</title> </head> <body> <h1>Profile Employee</h1> <form:form method="POST" modelAttribute="employee"> <table> <tr> <td><label>First Name</label></td> <td><form:input type="text" path="firstName" id="firstName" /> <form:errors path="firstName" style="color:red" /></td> </tr> <tr> <td><label>Last Name</label></td> <td><form:input type="text" path="lastName" id="lastName" /> <form:errors path="lastName" style="color:red" /></td> </tr> <tr> <td><label>Sex</label></td> <td><form:radiobutton path="sex" value="Male" />Male <form:radiobutton path="sex" value="Female" />Female <form:errors path="sex" style="color:red" /></td> </tr> <tr> <td><label>Date of birth</label></td> <td><form:input type="text" path="birthDay" id="birthDay" /> <form:errors path="birthDay" style="color:red" /></td> </tr> <tr> <td><label>Email</label></td> <td><form:input type="text" path="email" id="email" /> <form:errors path="email" style="color:red" /></td> </tr> <tr> <td><label>Country</label></td> <td><form:select path="country" id="country"> <form:option value="">Select Country</form:option> <form:options items="${countries}" /> </form:select> <form:errors path="country" style="color:red" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit"></td> </tr> </table> </form:form> </body> </html> |
and the another view looks like the following:
success.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Success Page</title> </head> <body> <table> <tr> <td><label>First Name:</label></td> <td>${employee.firstName}</td> </tr> <tr> <td><label>Last Name:</label></td> <td>${employee.lastName}</td> </tr> <tr> <td><label>Sex:</label></td> <td>${employee.sex}</td> </tr> <tr> <td><label>Date of birth:</label></td> <td>${employee.birthDay}</td> </tr> <tr> <td><label>Email:</label></td> <td>${employee.email}</td> </tr> <tr> <td><label>Country:</label></td> <td>${employee.country}</td> </tr> </table> </body> </html> |
Completely Project structure
Almost done, we have the completely project with structure like this image
Deploy Spring MVC Project in Eclipse Using Maven
We have finished for Creating Spring MVC Project in Eclipse Using Maven. It’s time we package the project into war file by using maven. Right click the project and select Run As -> Maven install. Then we have the spring-mvc-maven. war file in the target directory in the project. The file name is set in the pom.xml file.
We can run spring application by copying the above war file into webapps directory of Tomcat 8 or right click on the project in Eclipse Navigator and select Run As -> Run on Server. Accessing the URL http://localhost:8080/spring-mvc-maven/ and the screen should display such as below
We try to input data on the form like the picture
Then click button Submit, the screen displays our input like below
That’s all on the tutorial Creating Spring MVC Project in Eclipse Using Maven.
Download complete source code of example, please click link below
SpringMVC-Maven-Eclipse-Example.zip (606 downloads)
Nice
where is your model class?
Hi Assik,
Please download source code attachment
This website is really cool. I have bookmarked it.
Do you allow guest post on your site ? I can write high quality articles for you.
Let me know.
Hi Saul,
Thank for your talks. I will drop you email