Spring MVC : Hello World in 10 steps

Ok, so we are going to work on a critical customer requirement. When the customer enters the url http://localhost:9999/hello?name=Spring into the browser, it should display the message “Hello : Spring”.

Given below are the software versions that will be used for setting up this application.

Java : 1.8.0
Maven : 3.1.1

Setup the environment variables on your machine,

  • Add MAVEN_HOME/bin to the Path.
  • Set JAVA_HOME to the JDK installation location.
  • Verify that the settings are proper by running “mvn -version” command.

1. Create a webapp scaffolding using maven

D:\spring\>mvn archetype:generate -DgroupId=demo.web -DartifactId=spring-mvc-webapp-1 -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

This will create a new directory “spring-mvc-webapp-1” with all the required folder structure for a webapp including the web.xml file.

2. Replace your pom.xml with below file. This pom file has the spring dependencies and the jetty plugin configured properly.

<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.oracle.mds.web</groupId>
  <artifactId>webapp-1</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>webapp-1 Maven Webapp</name>
  <url>http://maven.apache.org</url>
 <properties>
 	<spring.version>4.0.1.RELEASE</spring.version>
 </properties>
 <dependencies>
	 <!-- Spring dependencies -->
	 <dependency>
	 <groupId>org.springframework</groupId>
	 <artifactId>spring-core</artifactId>
	 <version>${spring.version}</version>
	 </dependency>
	 
	 <dependency>
	 <groupId>org.springframework</groupId>
	 <artifactId>spring-web</artifactId>
	 <version>${spring.version}</version>
	 </dependency>
	 
	 <dependency>
	 <groupId>org.springframework</groupId>
	 <artifactId>spring-webmvc</artifactId>
	 <version>${spring.version}</version>
	 </dependency>
 </dependencies>
  <build>
  	<plugins>
 		<plugin>
  		<groupId>org.eclipse.jetty</groupId>
  		<artifactId>jetty-maven-plugin</artifactId>
		</plugin>
	</plugins>
 
    <finalName>webapp1</finalName>
  </build>
</project>

3. Generate eclipse metadata files by running “mvn eclipse:eclipse -Dwtpversion=2.0”
For maven newbees, run all maven commands from the root directory of the webapp (where pom.xml is found).

4. Import the project into eclipse

Open Eclipse and import the project into it using [File > Import > Existing Project into Workspace] option.

5. Open web.xml and replace the content with what is given below. This will configure the spring dispatcher servlet.

<web-app id="WebApp_ID" 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">
<display-name>Archetype Created Web Application</display-name>
<servlet>
   <servlet-name>dispatcher</servlet-name>
   <servlet-class>
       org.springframework.web.servlet.DispatcherServlet
   </servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
   <servlet-name>dispatcher</servlet-name>
   <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

6. Create dispatcher-servlet.xml under WEB-INF, with below content.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 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-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="demo.web.controller" />

 <bean
 	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 	<property name="prefix">
 		<value>/WEB-INF/views/</value>
 	</property>
 	<property name="suffix">
 		<value>.jsp</value>
 	</property>
 </bean>
</beans>

7. Add a new source folder “java” (under src/main) by right clicking the project and choosing [New > Source Folder]. Create a package demo.web.controller inside this folder.

8. Now lets create a simple HelloWorldController to handle our GET request and display the message back.

package demo.web.controller;

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 HelloWorldController 
{
 
	 @RequestMapping("/hello")
	 public String hello(
			 @RequestParam(value="name", required=false, defaultValue="World") 
			 String name, 
			 Model model) 
	{
		 model.addAttribute("name", name);
		 return "helloworld";
	 }
 
}

9. Create a “views” directory under WEB-INF and place the “helloworld.jsp” there.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<title>Spring4 MVC - HelloWorld</title>
	</head>
<body>
	<h1>Hello : ${name}</h1>
</body>
</html> 

10. Finally, it’s Demo time…!! Compile the application using “mvn clean install” and run it using “mvn jetty:run -Djetty.port=9999”. If everything went well, you should be able to access the application using the url – http://localhost:9999/hello?name=Spring.

Sample Java program to read XML from a file and print it

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class XMLReaderSample 
{
    public static void main(String[] args) throws Exception {
        Document doc = loadXMLFromFile("notes_sample.xml");
        
        printXML(doc);
    }
    
    public static Document loadXMLFromFile(String fileName) throws Exception
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        
        return builder.parse(new File(fileName));
    }
    
    public static void printXML(Document doc) throws TransformerConfigurationException, TransformerException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result =  new StreamResult(System.out);
        transformer.transform(source, result);        
    }
}

Get current swap usage for all running processes

#!/bin/bash
# Get current swap usage for all running processes
# Erik Ljungstrom 27/05/2011
SUM=0
OVERALL=0
for DIR in `find /proc/ -maxdepth 1 -type d | egrep “^/proc/[0-9]”` ; do
PID=`echo $DIR | cut -d / -f 3`
PROGNAME=`ps -p $PID -o comm –no-headers`
for SWAP in `grep Swap $DIR/smaps 2>/dev/null| awk ‘{ print $2 }’`
do
let SUM=$SUM+$SWAP
done
echo “PID=$PID – Swap used: $SUM – ($PROGNAME )”
let OVERALL=$OVERALL+$SUM
SUM=0

done
echo “Overall swap used: $OVERALL”

How to log iptables packet drops

Add following two lines to /etc/sysconfig/iptables

-A INPUT -m limit –limit 15/minute -j LOG –log-level 7 –log-prefix “Dropped by firewall: ”

-A OUTPUT -m limit –limit 15/minute -j LOG –log-level 7 –log-prefix “Dropped by firewall: ”

Restart iptables

In /etc/syslog.conf, add

kern.=debug     /var/log/firewall

Restart syslogger – /sbin/service syslog restart

 

useful mvn commands

To download sources, use – mvn dependency:sources

mvn eclipse:eclipse -DdownloadSources=true

To use maven jetty plugin, add below plugin to your pom,

<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
</plugin>

use command mvn org.mortbay.jetty:jetty-maven-plugin:run to start jetty.

To use the truncated command mvn jetty:run, add below lines to your settings file,

  <pluginGroups>
    <pluginGroup>org.mortbay.jetty</pluginGroup>
  </pluginGroups>

To create an Eclipse Web project using maven use - mvn eclipse:eclipse -Dwtpversion=1.5