Recently I was given a task to write a web-application. I didn’t have prior knowledge of web-application, so I started looking for simple Hello world!! tutorial. I found many tutorials, all of them were using some kind of IDE to write the application(and no wonder most of them were using Eclipse). But I was inclined to use only VI as an editor and wanted to handcraft each and every piece of the application. Only few tutorials helped me in bits-and-pieces to write my own handcrafted Hello Wold!! web-application. I thought to share it with others.
Prerequisite :
Build tool : Gradle (want to install gradle?)
Server : Apache tomcat 7.0.30
Development Language : Java

Let’s define the proper directory structure compatible with the gradle war plugin. The project directory structure is shown below.

 HelloWorldWebApp
    │       
    ├── build.gradle
    └── src
        └── main
            ├── java
            │   └── com
            │       └── code4reference
            │           └── mywebapp
            │               └── HelloWorldController.java
            └── webapp
                └── WEB-INF
                    ├── appContext
                    │   ├── mappings.xml
                    │   └── beans.xml
                    └── web.xml

Note : Here, com/code4reference/webapp is basically the package name in which the HelloWoldController.java is defined. This directory structure will change according to the package name. For creating the above directory structure, execute the commands given below.

mkdir -p HelloWorldWebApp/src/main/java/com/code4reference/mywebapp
mkdir -p HelloWorldWebApp/src/main/webapp/WEB-INF/appContext

Create HelloWorldController.java in mywebapp and put the following content. You will notice that greeting and hi methods are mapped to the same name url in mappings.xml file. These urls are automatically mapped by the Spring framework. If the method name and the url are different, the Spring will throw exceptions.

package com.code4reference.mywebapp;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.servlet.http.HttpServletResponse;

import java.util.Properties; 
import java.io.UnsupportedEncodingException;

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.bind.annotation.RequestMethod;

@Controller
public class HelloWorldController {
	private final static String PARAMETER_MESSAGE = "msg";

    /** The method below handles the 
     * url localhost:8080/HelloWorldWebApp/greeting?msg=Hello 
     * here 'Hello' can be any word which can be passed 
     * as msg variable value. 
     * Here, url parameter msg is mapped to message variable.
     **/ 
    @RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public String greeting(@RequestParam(value = PARAMETER_MESSAGE ) String message,
			           HttpServletResponse response) throws Exception {
			           
      System.out.println("Received param msg : "+ message);
       //The below string will appear on the brwoser window.
      return "<h3><i> Your greeting "+message + " </i></h3>";
	}

    /** The below method will handle the 
     *url localhost:8080/HelloWorldWebApp/hi 
     *
     **/ 
    @RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public String hi(HttpServletResponse response) throws Exception {
      //The below string will appear on the brwoser window.
      return "<h3><i> Hi!! This is your first simple webapp </i></h3>";
	}
}

Usually people create bean and URL mapping in web.xml but for better clarity and manageable code, we create two different files, called beans.xml and mappings.xml. beans.xml file will have the bean definition whereas mapping of bean to URL will be defined in mappings.xml file. These files will be imported to the web.xml.
Now, create file beans.xml in appContext directory and put the following content.

<?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:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>
   <bean id="HelloWorldController" 
         class="com.code4reference.mywebapp.HelloWorldController"/>
 </beans>

In the same directory create another file called mappings.xml file and put the following content.

<?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:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
   <context:annotation-config/>
   <bean id="commonServiceMappings" 
         class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
      <property name="mappings">
          <value>
             /greeting=HelloWorldController
             /hi=HelloWorldController
          </value> 
      </property>
   </bean>
</beans>

Now it’s time to define the web.xml file. Create the web.xml file in WEB-INF directory.

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
         version="2.4">
         
   <servlet>
      <servlet-name>dispatcher</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>
            /WEB-INF/appContext/mappings.xml
            /WEB-INF/appContext/beans.xml
         </param-value>
      </init-param>
   </servlet>

   <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>
  <!-- Don't remove the below section-->   
   <welcome-file-list>
    <welcome-file></welcome-file>
   </welcome-file-list>
</web-app>

You may have noticed that mappings.xml and beans.xml have been imported to web.xml. Now its time to build the application for which we will write the gradle script. Create build.gradle file in HelloWoldWebApp directory and put the following content.

apply plugin: 'java'
apply plugin: 'war'

repositories {
   mavenCentral()
}
dependencies {
        compile 'org.springframework:spring-webmvc:3.0.5.RELEASE'
        compile 'commons-codec:commons-codec:1.4'
        providedCompile "javax.servlet:servlet-api:2.5"
        
}

Here Java and War plugin have been used to compile the java source code and to build the war file respectively. Gradle war plugin expects the java source code in src/main/java and the web configuration file in src/main/webapp/WEB-INF folder. Notice that compile time dependencies are included in the dependencies section of the gradle script. The Gradle takes care of including the dependencies jar files in the war file. Once done, just execute the following command in HelloWoldWebApp folder

gradle war

Gradle creates the war file in build/libs directory. Now put the HelloWorldWebApp.war in [apache-tomcat-home-directory]/bin/webapps and restart the tomcat.

Note : If Apache-tomcat 7.0 is installed in your system, then you don’t need to restart the tomcat. Tomcat identifies new web-application, deploys it and restarts itself

Once the tomcat is restarted, hit “http://localhost:8080/HelloWorld/hi” on browser. You will see this line “Hi!! This is your first simple webapp” on webpage. Even you can try with this url “http://localhost:8080/HelloWorld/greeting?msg=Hellothere”, try to change the word “Hellothere” and hit the url. The message displayed on the webpage changes accordingly.

Trackback

only 1 comment untill now

  1. Code4ReferenceHandcrafted Hello world web-application in Java…

    Thank you for submitting this cool story –

Add your comment now