Spring 4 web application example. How to Setup Spring in eclipse with maven. steps

In this tutorial, let us create a web application (SpringSample) using the MVC frame work Spring version 4 in easy steps with the help of Maven in Eclipse.

The Technology used in this exampe

1. Spring 4.1.4
2. Java 1.8
3. Maven
3. Eclipse with Apache server

Step 1: Create an empty project (MyFirstSpringApp) with maven

Run the following command in the command prompt in a folder where you want to create the work space (In this example : f:\Eclipse)

f:\Eclipse> mvn archetype:generate -DgroupId=net.javaonline -DartifactId=MyFirstSpringApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

To run the above command, please ensure that maven is installed in your local machine. If not, please go through my earlier tutorial, how to install maven in windows 8?.

When you run the above command, it creates a web application (MyFirstSpringApp) with in the current folder (F:\Eclipse\MyFirstSpringApp) with maven pom.xml

Step 2: Add Spring Dependencies for the project using maven i.e add necessary lines in the pom.xml to load necessary jars from mavan repository

	<dependencies>
		<!--  SPRING DEPENDENCIES -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.1.4.RELEASE</version>
	    </dependency>

 		<dependency>
 			<groupId>org.springframework</groupId>
 			<artifactId>spring-web</artifactId>
 			<version>4.1.4.RELEASE</version>
 	   </dependency>

 	   <dependency>
 			<groupId>org.springframework</groupId>
 			<artifactId>spring-webmvc</artifactId>
 			<version>4.1.4.RELEASE</version>
 	  </dependency>       

	</dependencies> 

The complete pom.xml file for the project is given below. You can simply replace it with existing one in the project. (i.e. in the folder F:\Eclipse\MyFirstSpringApp

<?xm	l version="1.0" encoding="UTF-8"?>

<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/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javaonline</groupId>
	<artifactId>SpringSample</artifactId>
    <packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
		<!-- TODO project name  -->
	<name>SpringSample</name>
	<description></description>

	<dependencies>
		<!--  SPRING DEPENDENCIES -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.1.4.RELEASE</version>
	    </dependency>

 		<dependency>
 			<groupId>org.springframework</groupId>
 			<artifactId>spring-web</artifactId>
 			<version>4.1.4.RELEASE</version>
 	   </dependency>

 	   <dependency>
 			<groupId>org.springframework</groupId>
 			<artifactId>spring-webmvc</artifactId>
 			<version>4.1.4.RELEASE</version>
 	  </dependency>       

	</dependencies>
	<build>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
			<resource>
				<filtering>false</filtering>
				<directory>src/main/java</directory>
				<includes>
					<include>*</include>
				</includes>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<filtering>false</filtering>
				<directory>src/test/resources</directory>
			</testResource>
			<testResource>
				<filtering>false</filtering>
				<directory>src/test/java</directory>
				<includes>
					<include>**</include>
				</includes>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</testResource>
		</testResources>
		<plugins>
			<plugin>
				<inherited>true</inherited>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>UTF-8</encoding>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>

		</plugins>
	</build>

	</project> 

Step 3: Replace the existing web.xml file located in the folder (F:\Eclipse\MyFirstSpringApp\src\main\webapp\WEB-INF) with the below web.xml file.

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

  <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>.do</url-pattern>
  </servlet-mapping>
</web-app>

In web.xml, you have to mention the Controller Servlet and its mapping. org.springframework.web.servlet.DispatcherServlet is the Front Controller servlet and the mapping is .do. All the requests with the URL pattern .do will be routed to the controller servlet.

Step 4: Go to the Command Prompt, Change to the folder F:\Eclipse\MyFirstSpringApp and run the below command to build the project

F:\Eclipse\MyFirstSpringApp> mvn eclipse:eclipse -Dwtpversion=2.0

Step 5: Open the Eclipse and import the workspace created using File->Import->Existing projects into work space. Select the folder MyFirstSpringApp and submit.

Step 6: Create an XML file called springapp-servlet.xml (spring-servlet.xml=dispatcher servlet name “springapp” + “-servlet.xml”) which will contain all beans.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    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-2.0.xsd">

    <!-- the application context definition for the springapp DispatcherServlet -->

    <bean name="/myBean" class="net.javaonline.spring.MyFirstSpringController"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/Pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans> 

Step 7: Let us create an Web Controller (MyFirstSpringController.java) a java class that receives http request for /hello, transforms it into model and returns to the view (hello.jsp).

MyFirstSpringController.java

MyFirstSpringController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MyFirstSpringController {

	  @RequestMapping("/hello")
	    public String test(@RequestParam(value="name", required=false, defaultValue="XYZ") String name, Model model) {
	    	System.out.println("Request Received");
	        model.addAttribute("name", name);
	        return "hello";
	    }
}

The above controller accepts the input parameter “name” and passed to the view page. Default value is XYZ, if no parameter or no value is sent. Below is the view code to render the output.

View (hello.jsp)

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>My First Spring App</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<table>
<tr>
<td>Hello Mr.  ${name} </td>
</tr>
</table>
</body>
</html>

The Final Project Directory Structure will be as follows

My first spring app structure

 

Libraries:

libraries

Now you can compile and run the application by calling the below URL in the browser.

http://localhost:8080/SpringSample/hello.do?name=Jacob

Output :

Spring My First App Output

 

Note : If your get the below error when you run the above application, please include src/main/java folder in the build path

java.lang.ClassNotFoundException: net.javaonline.spring.MyFirstSpringController

 

Reference :Spring web application

You may also like

Leave a Reply