Tutorial Maven Spring

From HaFrWiki
Jump to: navigation, search

Tutorials help the developer in exploring how application can be made. The tutorials here presented try to to do that too. The examples are from various parts of the Internet and are always presented with reference to the original side.

To understand the presented examples pre-required knowledge is necessary on:

  • Language Java JDK 1.8 and JEE
  • Build tool Maven (Version 3 or better)
  • IDE Eclipse (Luna or better)
    • with JEE
    • and m2eclipse Apache Maven plug-in.
  • Web Container Tomcat (8.0 or better)
  • Spring MVC
  • AJAX tool jQuery (1.8 or better)

Tomcat Installation[edit]

Tomcat settings using eclipse.

If you don't have installed Tomcat:

  • Download Tomcat
  • MAMP Installed:
    • Copy the unzipped download of Tomcat to the directory /Applications/MAMP.
    • Make all the *.sh file and the *.jar files in the directory /Applications/MAMP/<Apache-Tomcat-Dir>/bin executable
      $ chmod +x *.sh
      $ chmod +x *.jar
    • Make alias for the starttomcat and stoptomcat in the ~.bashrc file
  • Adjust the settings for the access to tomcat in /Applications/MAMP/<Apache-Tomcat-Dir>/conf/tomcat-users.xml.
   <role rolename = "tomcat"           />
   <role rolename = "manager-gui"      />
   <role rolename = "manager-status"   />
   <role rolename = "manager-script"   />
   <role rolename = "manager-jmx"      />
   <role rolename = "admin-gui"        />
   <user username="mpro" password="XXXXXXXX" roles="tomcat,manager-gui,manager-status,manager-script,manager-jmx,admin-gui" />

Eclipse common problems[edit]

Maven[edit]

The Web Deployment Assembly (Part of the properties of yourDynamic Web Project needs to have a packaging Structure for Maven the Maven Dependencies (located at /WEB-INF/lib).
If you have not added these dependencies you receive an error like:

SEVERE: Servlet [crunchify] in web application [/CrunchifySpringMVCTutorial] threw load() exception
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Server[edit]

Be aware to include the Tomcat server.


Tomcat Specifics[edit]

When you start tomcat (http://localhost:8080) all settings can now be (re)viewed. But when using Tomcat from eclipse, suddenly these settings are not accessible/unavailable. To prevent this behaviour do the following steps:

  • If application are installed in Tomcat with eclipse, remove these apps in the server view by right-mouse-click on the server (Tomcat vx.x Server...) and choose Add and Remove.
  • Now remove all applications.
  • Publish your settings (right mouse click on Server and select Publish).
  • In the server view, again Double click on the server and now the fields on the Server Locations tab are NOT gray out.
  • Now select Use Tomcat installation. (takes control of Tomcat installation).

Secondly you may get an error when working with eclipse: The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path.
To fix the problem, right click on project -> Properties -> Java Build Path -> Add Library...-> Server Runtime -> Apache Tomcat -> Finish.

Basic Maven Tomcat Deployment[edit]

Procedure will help you create a new web application using the m2eclipse Apache Maven plugin for Eclipse, and then deploy and run it on the Tomcat server defined in your Eclipse IDE [1].

  • In Eclipse, create a new Maven Project. File > New > Other... > Maven Project.
  • Accept the first Screen, choose Next
  • In the second Screen find and select the maven archetype called maven-archetype-webapp,

[ToDo Finish this example with pictures and annotations.]

Hello World[edit]

Tutorial for Spring MVC HelloWorld Using Maven in Eclipse [2].

Java developers often rely on examples to learn Spring framework. Simple examples are often a key learning resource. There are many Spring MVC HelloWorld applications. However, most of them are outdated (do not integrate Maven, use old version of Spring, etc) or not complete (missing key steps or file hierarchy view). All steps for creating a Spring MVC HelloWorld application using Maven in Eclipse are illustrated with as much details as necessary.

Prerequisite are installed versions of:

  • Java 7 or higher
  • Eclipse Kepler Java EE
  • Tomcat 7 or higher

[ToDo Finish this example with pictures and annotations.]

Hello World II[edit]

Tutorial of Crunchify [3] to create the most simple Hello World with the pre required tooling:

  • Tomcat 7.0.56 or Higher
  • Eclipse IDE Luna Service Release 1 v4.4.1 or higher (don'y forget the JEE
  • Spring 4.1.1 (No download required)
  • Java JDK 1.7 or higher
Step 1: Open Eclipse and Create Dynamic Web Project CrunchifySpringMVCTutorial.[edit]
1. Open > New > Dynamic Web Project

Settings for the project (See right image)

  1. Apache Tomcat v8.0
  2. Dynamic wen module version: 3.1
2. Create a standalone Dynamic Web Project


Step 2: Convert Project to a Maven Project[edit]

Right click on the project and Choose

3. Right click on the project and Choose...
4. Convert to Maven Project
Step 3: Add Spring Dependencies[edit]
5. Adding Maven dependencies
6. Maven Dependencies

I have uodated the version to 4.1.5 release of Spring. Your POM file should look like:

<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>CrunchifySprintMVCTutorial</groupId>
  <artifactId>CrunchifySprintMVCTutorial</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>4.1.5.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-aop</artifactId>
  		<version>4.1.5.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>4.1.5.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-web</artifactId>
  		<version>4.1.5.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.servlet</groupId>
  		<artifactId>jstl</artifactId>
  		<version>1.2</version>
  	</dependency>
  	<dependency>
  		<groupId>commons-logging</groupId>
  		<artifactId>commons-logging</artifactId>
  		<version>1.1.3</version>
  	</dependency>
  </dependencies>
</project>
Step 4: Create Spring Configuration Bean[edit]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	    xmlns:context="http://www.springframework.org/schema/context"
	    xsi:schemaLocation="http://www.springframework.org/schema/beans
                                              http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                                              http://www.springframework.org/schema/context 
                                              http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
	<context:component-scan base-package="com.crunchify.controller" />
 
	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix"       value="/WEB-INF/jsp/" />
		<property name="suffix"        value=".jsp" />
	</bean>
</beans>

Creates Spring Configuration Bean file /WEB-INF/crunchify-servlet.xml.

In the above crunchify-servlet.xml configuration file, we have defined a tag <context:component-scan>.

  1. This will allow Spring to load all the components from package com.crunchify.controller and all its child packages.
  2. This will load our CrunchifyHelloWorld.class.

Also we have defined a bean viewResolver.

  1. This bean will resolve the view and add prefix string /WEB-INF/jsp/ and suffix .jsp to the view in ModelAndView.


Note that in our CrunchifyHelloWorld class, we have return a ModelAndView object with view name welcome. This will be resolved to path /WEB-INF/jsp/welcome.jsp .

Step 5: Map Spring MVC in /WEB-INF/web.xml[edit]

If you do not have a /WEB-INF/web.xml you can generate one by:

  • Right mouse click on the project in the navigator.
  • Choose Java EE Tools > Genrate Deployment Descriptor.
<?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" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

	<display-name>CrunchifySpringMVCTutorial</display-name>
  	<welcome-file-list>
    	<welcome-file>index.jsp</welcome-file>
  	</welcome-file-list>
  
    <servlet>
        <servlet-name>crunchify</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>crunchify</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
  
</web-app>

The above code in web.xml will map DispatcherServlet with url pattern *.html. Also note that we have define index.jsp as welcome file.

One thing to note here is the name of servlet in <servlet-name> tag in web.xml.
Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application.
In this example, the framework will look for file called crunchify-servlet.xml.

Step 5: Create the Controlller Class[edit]

Create Controller Class.

  • Package: com.crunchify.controller
  • Filename: CrunchifyHelloWorld.java
1. Creates the Controller Class
package com.crunchify.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
/*
 * author: Crunchify.com
 * 
 */
 
@Controller
public class CrunchifyHelloWorld {
 
	@RequestMapping("/welcome")
	public ModelAndView helloWorld() {
 
		String message = "<br><div align='center'>"
				+ "<h3>********** Hello World, Spring MVC Tutorial</h3>" 
				+ "This message is comming " 
                                + "from CrunchifyHelloWorld.java **********<br><br>";
		return new ModelAndView("welcome", "message", message);
	}
}

Note that we have annotated the CrunchifyHelloWorld class with @Controller and @RequestMapping("/welcome"). When Spring scans our package, it will recognize this bean as being a Controller bean for processing requests. The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /welcome in the URL path. That includes /welcome/* and /welcome.html.

The helloWorld() method returns ModelAndView object. The ModelAndView object tries to resolve to a view named “welcome” and the data model is being passed back to the browser so we can access the data within the JSP. The logical view name will resolve to /WEB-INF/jsp/welcome.jsp . Logical name “welcome” which is return in ModelAndView object is mapped to path /WEB-INF/jsp/welcome.jsp.

The ModelAndView object also contains a message with key “message” and Detailed value. This is the data that we are passing to our view. Normally this will be a value object in form of java bean that will contain the data to be displayed on our view. Here we are simply passing a string.

Step 7: The View: Create /WebContent/index.jsp and /WebContent/WEB-INF/jsp/welcome.jsp file[edit]
<html>
<head>
<title>Spring MVC Tutorial Series by Crunchify.com</title>
<style type="text/css">
body {
	background-image: url('http://crunchify.com/bg.png');
}
</style>
</head>
<body>
	<br>
	<div align='center'>
		<h2>
			Hey You..!! This is your 1st Spring MCV Tutorial..<br> <br>
		</h2>
		<h3>
			<a href="welcome.html">Click here to See Welcome Message... </a>(to
			check Spring MVC Controller... @RequestMapping("/welcome"))
		</h3>
	</div>
</body>
</html>

Creates /WebContent/index.jsp

<html>
<head>
<title>Spring MVC Tutorial by Crunchify - Hello World Spring MVC
	Example</title>
<style type="text/css">
body {
	background-image: url('http://crunchify.com/bg.png');
}
</style>
</head>
<body>${message}
 
	<br>
	<br>
	<div align='center'
		style="font-family: verdana; padding: 10px; border-radius: 10px; font-size: 12px;">
 
		Spring MCV Tutorial by <a href="http://crunchify.com">Crunchify</a>.
		Click <a
			href="http://crunchify.com/category/java-web-development-tutorial/"
			target="_blank">here</a> for all Java and <a
			href='http://crunchify.com/category/spring-mvc/' target='_blank'>here</a>
		for all Spring MVC, Web Development examples.<br>
	</div>
</body>
</html>

Creates /WebContent/WEB-INF/jsp/welcome.jsp

Step 8: Review and Test[edit]
Review the navgator

Review your navigator

Resulting in ....

After visiting http://localhost:8080/CrunchifySprintMVCTutorial/welcome.html to see the result.

AJAX with Sprint MVC[edit]

Cruchify AJAX example [4] is based on the above Hello World example.

  • Tomcat 7.0.56 or Higher
  • Eclipse IDE Luna Service Release 1 v4.4.1 or higher (don'y forget the JEE
  • Spring 4.1.1 (No download required)
  • Java JDK 1.7 or higher
  • Jquery 1.10.1 or later
<html>
<head>
<!--
    Enables ajax in Spring MVC with jQuery 1.10. 
 -->
<title>Crunchify - Spring MVC Example with AJAX call</title>

<style type="text/css">
body {
	background-image:
		url('http://cdn3.crunchify.com/wp-content/uploads/2013/03/Crunchify.bg_.300.png');
}
</style>

<script type="text/javascript"
	src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
	function crunchifyAjax() {
		$.ajax({
			url : 'ajaxtest.html',
			success : function(data) {
				$('#result').html(data);
			}
		});
	}
</script>

<script type="text/javascript">
	var intervalId = 0;
	intervalId = setInterval(crunchifyAjax, 3000);
</script>
</head>

<body>
	<div align="center">
		<br> <br> ${message} <br> <br>
		<div id="result"></div>
		<br>
		<p>
			by <a href="http://crunchify.com">Crunchify.com</a>
		</p>
	</div>
</body>
</html>

1. The jspfile WEBINF/jsp/ajax.jsp

package com.crunchify.controller;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.Random;
 

/**
 * Class <code>CrunchifySprintAjaxJQuery</code> implements AJAX jQuery calls in Spring Framework.
 * 
 * @author Harm Frielink
 *
 */
@Controller
public class CrunchifySpringAjaxJQuery {
 
    @RequestMapping("/ajax")
    public ModelAndView helloAjaxTest() {
        return new ModelAndView("ajax", "message", "Crunchify Spring MVC with Ajax and JQuery Demo..");
    }
 
    @RequestMapping(value = "/ajaxtest", method = RequestMethod.GET)
    public @ResponseBody
    String getTime() {
 
        Random rand = new Random();
        float r = rand.nextFloat() * 100;
        String result = "<br>Next Random # is <b>" + r + "</b>. Generated on <b>" + new Date().toString() + "</b>";
        System.out.println("Debug Message from CrunchifySpringAjaxJQuery Controller.." + new Date().toString());
        return result;
    }
}	// CrunchifySpringAjaxJQuery

2. The Java Class File CrunchifySpringAjaxJQuery located in src/com/crunchify/controller/.

See also[edit]

top

  • Projects Spring IO, Spring Framework.
  • Crunchify Tutorials
  • Spring Framework (Spring.io)
    • Spring Guides, Whatever you're building, these guides are designed to get you productive as quickly as possible – using the latest Spring project releases and techniques as recommended by the Spring team.
    • Spring Tutorials, Designed to be completed in 2-3 hours, these guides provide deeper, in-context explorations of enterprise application development topics, leaving you ready to implement real-world solutions.
    • Spring Docs, Quick access to API and reference documentation for all Spring projects

Reference[edit]

top

  1. Base22, How to make a Maven web app with Tomcat, by
  2. Program Creek, Spring MVC HelloWorld Using Maven in Eclipse, by X Wang.
  3. Cruchify , Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips
  4. Cruchify, How to use AJAX, jQuery in Spring Web MVC (.jsp),