2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Developing a Spring MVC project/application from scratch using Maven for novice


There are numbers of web sites available where you can find the complete Spring MVC example then, why again? Definitely the question will come. Its very simple as per my experience and observation found that most of the site come up with the incomplete information and the given code deal will lot of error prone and also few of them are outdated too.  Because when a novice come and start application development initially he/she don't have enough knowledge to troubleshot the exceptions hence that leads to consume a huge amount of time.In this post those things are properly taken care so that anybody can just follow the given steps and come up with the success.

If anybody came from struts background its very easy to catch this framework because both are developed by following the MVC architecture.Or if not also its not a big deal to learn this framework just skip the above comparison and start with a fresh atmosphere.

Abount Spring Framework and Spring MVC

Today spring is one of the most popular application development framework of the Java enterprise world.Now a days Million and Million of developers around the world are the big fan of this.This Framework providing to create high performing, easily testable, reusable code and it is lightweight too.As we know that, Spring framework is an open source Java platform and initially written by Rod Johnson which was for first time released under the Apache 2.0 license in June 2003.

Spring includes a powerful and highly configurable MVC web framework.Spring's MVC model is most similar to that of Struts, although it is not derived from Struts. A Spring Controller is similar to a Struts Action in that it is a multithreaded service object, with a single instance executing on behalf of all clients. However, we believe that Spring MVC has some significant advantages over Struts. For example:

  • Spring provides a very clean division between controllers, JavaBean models, and views.
  • Spring's MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.
  • Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.
  • Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it.
  • Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.
  • Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
  • The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.

Development of Spring MVC Application from scratch

Its explain you each of the steps with more coding and less description to complete the application. Just follow me up as per the steps to see the result in one shot.

Step - 1 - Development environment

Environment Prerequisites

  1. JDK 1.5 or above 
  2. Eclipse any version compatible with maven tool and capable to create and run enterprise applications.
  3. Java web server or application server.
  4. Spring Release version 4.0 or above.

Software used for the demonstration

  • Eclipse Mars.2
  • jdk1.8.0_102
  • wildfly-10.0.0.Final
  • Spring 4.3.1.RELEASE

Step - 2 - Create maven web project

Open eclipse -> Select or create workspace -> Go to File menu then New and chose other -> type maven from wizard search [Image - 1] -> Select Maven Project and click on Next -> Check out on Create a simple project [Image - 2] if its unchecked and click on Next ->

fill out the Artifacts like group id and artifact id etc [Image - 3] and click on Finish -> Open Project explorer and expand the newly created maven web project [Image - 4]

Please note if any error message displaying on the project then troubleshot yourself because it may incompatible with the eclipse version used or any environmental issue like version and all.That need to take care if any.

Step - 3 - Configure Web or Application server instance.
The application is developing with the use of maven tool so this step is optional. You may configure the server instance through eclipse or simply skip.
If you don't configure the run time server instance with the application it will not compile successfully because it is a java enterprise based MVC application which needs servlet and jsp apis as a minimal requirement.
So there are two options are available to progress, either need to add a server instance and intimate to the application or provide the dependency through pom for the successful compilation.

Step - 4 - Project configuration

a. Dependency configuration

Open pom.xml and replace with the below content.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>springmvcapp</groupId> <artifactId>springmvcapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>compile</scope> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </build> </project>

b. Enabling Spring MVC by adding configuration and initialization classes

package com.framework.mvc.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.framework.mvc.controller") public class SpringConfiguration { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }

package com.framework.mvc.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { SpringConfiguration.class }; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }

Step - 5 - Coding the Controller and View

a. Controller

package com.framework.mvc.controller;
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("/")
public String firstCall(ModelMap model) {
public class GreetingController { @RequestMapping(method = RequestMethod.GET) public String firstCall(ModelMap model) { model.addAttribute("message", "Welcome to Spring MVC Framework"); return "welcome"; } @RequestMapping(value = "/home", method = RequestMethod.GET) public String getHomePage(ModelMap model) { model.addAttribute("message", "The world of Spring"); return "welcome"; } }

b. View 

Create a folder WEB-INF inside webapp then create another folder views WEB-INF and create a jsp file with name welcome.jsp and place the below content

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head>
<body> ${message}

Step - 6 - Application deployment and execution

This is the final step of this development to see the final result.

  1. Right click on the application (springmvcapp) and run as maven install and to build successfull.
  2. Refresh the project go to target folder and copy the war file 'springmvcapp-0.0.1-SNAPSHOT.war'.
  3. Place the war file into the deployment folder of the server manually.
  4. Start the server and wait till its start successfully.
  5. Once server started properly, open the browser and go to the url localhost:8080/springmvcapp-0.0.1-SNAPSHOT or localhost:8080/springmvcapp-0.0.1-SNAPSHOT/home to see the result.
  6. Once the messages will appear into the browser close the browser and stop the server to relax  for a moment.

Detail description of the spring annotations being used here

  • @Configuration - annotation is used to mark a class as a source of the bean definitions. Beans are the components of the system that you want to wire together.
  • @EnableWebMvc - annotation is equivalent to <mvc:annotation-driven /> in XML. It enables support for @Controller-annotated classes that use @RequestMapping to map incoming requests to a certain method.
  • @ComponentScan - annotation is delivering the meta informations to spring that is about the configuration classes and can initialize the beans correctly. It makes Spring scan the packages configured with it for the @Configuration classes.
  • @Bean - A method marked with the @Bean annotation is a bean producer. Spring will handle the life cycle of the beans for you, and it will use these methods to create the beans.
  • @Controller - annotation marks the class as a web controller, capable of handling the HTTP requests. Spring will look at the methods of the class marked with the @Controller annotation and establish the routing table to know which methods serve which endpoints.
  • @RequestMapping - The @RequestMapping(method = RequestMethod.GET, value = “/path”) annotation specifies a method in the controller that should be responsible for serving the HTTP request to the given path. Spring will work the implementation details of how it’s done. You simply specify the path value on the annotation and Spring will route the requests into the correct action methods.
  • @Component[Not used here] - Another way to declare a bean is to mark a class with a @Component annotation. Doing this turns the class into a Spring bean at the auto-scan time.

You can also refer to spring-annotations know more about maximum number of annotations being used with spring.

Conclusion (Its the time to conclude the topic with few more lines)

This post more simplified so that any of the user who want to learn and develop a spring MVC application from the application from the scratch able to follow up the steps without any inconsistency. Please leave a comment if any of the steps are not proper or if anybody found any wrong content provided here. I will take care accordingly. Hope the content provided here is understandable and beneficial.

Thank you and Happy coding!!!