The first real example I will post, is a basic set-up for a Spring MVC project. This example will use the following components:
- Maven for build, dependencies and running a simple container with jetty.
- Spring-webmvc framework for server side handling
- log4j for logging
- jQuery for client side Ajax
To use this example, you can do one out of three things:
- Download it directly as zip or tar.gz
- Use mercurial and get it with hg clone https://bitbucket.org/torbdani/yacebgettingstarted
- Follow my tutorial and try it yourself:
Step-by-step do it yourself:
First of you need to create a POM-file that Maven uses to build your project. Name it “pom.xml”. Now paste the following into it:
<?xml 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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.yaceb.examples</groupId> <artifactId>gettingStarted</artifactId> <version>1.0</version> <packaging>war</packaging> <build> <plugins>and we are done <!--Override default behavior and set java version to 1.6--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!--We need this to make a war for when we deploy to a container--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> </plugin> <!--Lightweight container for testing locally--> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.26</version> <!--So we dont have to use the project name in the URL --> <configuration> <contextPath>/</contextPath> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> </dependencies> </project>
This first part is just XML meta-data.
<?xml 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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
This is meta-data about this project.
<groupId>net.yaceb.examples</groupId> <artifactId>gettingStarted</artifactId> <version>1.0</version> <packaging>war</packaging>
The plugin part is plugins that you can use with Maven.
The last part is where you tell Maven what your project depends on to compile.
Now you have everything you need to get started on the actual code.
Start by creating the following folders in the same directory as your pom.xml:
src/main/java
src/main/resources
src/main/webapp/WEB-INF/
In the WEB-INF folder create a file with the name “web.xml” and paste the following:
<?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"> <!--Spring will default to this location if you don't set contextConfigLocation but I have it here so there will be no magic involved--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/applicationContext.xml</param-value> </context-param> <!--This listener will start the spring framework--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--This servlet will map all the requests to our controllers--> <servlet> <servlet-name>yacebExamples</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>namespace</param-name> <param-value>applicationContext</param-value> </init-param> </servlet> <!--We want to map everything to our spring servlet--> <servlet-mapping> <servlet-name>yacebExamples</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
This is a basic configuration that the container that runs your web application will read from.
In the WEB-INF folder we want some configuration for Spring, so we must create a file called “applicationContext.xml” (you can see in the web.xml we tell Spring to look for a file called applicationContext.xml in the WEB-INF folder). You can paste the following into the file:
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- We want to use annotations to configure beans: --> <context:annotation-config/> <!-- This is the package to scan for beans (@Compontent, @Controller etc): --> <context:component-scan base-package="net.yaceb.examples"/> <!-- We want to use Spring MVC, configured by annotations --> <mvc:annotation-driven/> <!--If you need to add static files to your webapp, you need to do something similar to the following, since our servlet mapping maps everything to spring, we have to tell spring where to find static files--> <!-- uncomment to use this <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/gfx/**" location="/gfx/" /> <mvc:resources mapping="/js/**" location="/js/" /> --> <!--This adds headers to the requests so that browsers don't use cache. Avoids problems when developing--> <mvc:interceptors> <bean id="webContentInterceptor" > <property name="cacheSeconds" value="0"/> <property name="useExpiresHeader" value="true"/> <property name="useCacheControlHeader" value="true"/> <property name="useCacheControlNoStore" value="true"/> </bean> </mvc:interceptors> <!--Tells spring where to find its views--> <bean id="viewResolver" p:prefix="/jsp/" p:suffix=".jsp"/> </beans>
As you can see in the part where it says:
<context:component-scan base-package="net.yaceb.examples"/>
We tell Spring to search for beans in the package “net.yaceb.examples”, so in the folder “src/main/java” add the folders “net/yaceb/examples” and create a file called “MainController.java” with the following content:
package net.yaceb.examples.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MainController {
@RequestMapping("/index.html")
public ModelAndView index(){
return new ModelAndView();
}
@RequestMapping("/hello")
@ResponseBody
public String hello(@RequestParam("name") String name){
return "Hello " + name + "!";
}
}
@Controller tells Spring this class is a controller.
@RequestMapping maps URL’s to a method. Defaults to a GET request
@ResponseBody maps the response to a suitable format, in this case simple text, but can also be json for objects.
@RequestParam(“name”) takes a given GET parameter and inserts it to the following value.
Now that you have a controller, the only thing missing is a jsp-file. If you look in applicationContext.xml you can see that we had the following:
<bean id="viewResolver" p:prefix="/jsp/" p:suffix=".jsp"/>
This tells Spring where to find its views. In the folder “src/main/webapp/” add a folder called “jsp” and add a file called “index.jsp” with this content:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Simple example page</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
</head>
<body>
<label for="name">Input name: </label>
<input id="name"/>
<button onclick="showHello()">Submit</button>
<div id="txt">Output</div>
<script type="text/javascript">
function showHello() {
var str = $("#name").val();
if (str == "") {
$("#txt").html("");
} else {
$.get("/hello", {name: str}, function(data) {
$("#txt").html(data);
});
}
}
</script>
</body>
</html>
This creates an input field and a button. When you press the button, the string you typed will be sent server side to your controller with the help of jQuery. There your method will take the string, add “Hello ” in front and an exclamation mark at the back of the string, then send it back to the client where the whole string will be presented.
Optional:
in the folder “src/main/resources” create a file called “log4j.properties” with the content:
# Set root logger level to DEBUG and its only appender to sout. log4j.rootLogger=DEBUG, sout # sout is set to be a ConsoleAppender. log4j.appender.sout=org.apache.log4j.ConsoleAppender # sout uses SimpleLayout. log4j.appender.sout.layout=org.apache.log4j.SimpleLayout
Now change the content of your MainController.java to this:
package net.yaceb.examples.controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by IntelliJ IDEA.
* User: Torbjørn Danielsen
* Date: 10/30/11
* Time: 3:40 PM
*/
@Controller
public class MainController {
private static final Logger logger = Logger.getLogger(MainController.class);
@RequestMapping("/index.html")
public ModelAndView index(){
return new ModelAndView();
}
@RequestMapping("/hello")
@ResponseBody
public String hello(@RequestParam("name") String name){
logger.debug("Got request with name: " + name);
return "Hello " + name + "!";
}
}
This enables logging for your project. Your file structure should look like this:
To start this application open a shell and go to the root of the project where the pom.xml file is and type “mvn jetty:run”. Go to the following address to test your code: http://localhost:8080/index.html
Hopefully, this was a helpful post to get you started. If you have any feedback, please let me know in the comments.

Recent Comments