Saturday, 13 July 2013

Spring MVC 3.0 - Hello World !!

Introduction - Spring Framework is a lightweight alternative to Java EE's complexity. Designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for uploading files. I don't want you to read another bunch of lines and make you bore instead look at the flow diagram below which will explain the working of Spring MVC.

















Image Source - Spring MVC Work Flow 


Lets develop a small Hello World Program using Spring MVC 3

Jars Needed

commons-logging-1.0.4.jar
jstl-1.2.jar
org.springframework.asm-3.0.1.RELEASE-A.jar
org.springframework.beans-3.0.1.RELEASE-A.jar
org.springframework.context-3.0.1.RELEASE-A.jar
org.springframework.context-sources-3.0.1.RELEASE-A.jar
org.springframework.core-3.0.1.RELEASE-A.jar
org.springframework.expression-3.0.1.RELEASE-A.jar
org.springframework.jdbc-3.0.1.RELEASE-A.jar
org.springframework.web-3.0.1.RELEASE-A.jar
org.springframework.web.servlet-3.0.1.RELEASE-A.jar

web.xml

Define a servlet and named it as dispatcher. You can name it whatever you want.

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>helloworld</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <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>


dispatcher-servlet.xml

Create an xml and name it as <name of the dispatcher servet>-servlet.xml. This is the front controller which will handle all your request coming from web.xml. Since we have defined the url mappings above. Thus any request after '/' will be delegated to this dispatcher-servlet.xml.
With Spring MVC 3 we are using the power of annotations. <context:component-scan base-package="controller" /> will look out for the controller package (or you can name it whatever u want like handler) where it can map the incoming request using @RequestMapping annotation.
Define bean viewResolver which will show the jsp as per the request sent from controller.


<?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:flow="http://www.springframework.org/schema/webflow-config"
       xmlns:context="http://www.springframework.org/schema/context"
       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">
         
 <context:component-scan base-package="controller" />
 
 <bean id="viewResolver"
     class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix"><value>/jsp/</value></property>    
      <property name="suffix"><value>.jsp</value></property>
    </bean>
         
</beans>


controller class

With the controller class we are using ModelAndView object to return the view name which is to be displayed. You can see that using the annotation we have mapped the incoming request to handleLoginRequest() method.

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {
 
 @RequestMapping("/login")
 public ModelAndView handleLoginRequest()
 {
  return new ModelAndView("login");
 }

}


jsp

Create a jsp and name it as login.jsp and provide your content whatever you want to display.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Suncity Health Club - Login </title>
</head>
<body>
Hi Ankit !! Welcome to Spring MVC
</body>
</html>

output

open your browser and type http://localhost:8080/<projectName>/login

Also I have added a snapshot of folder hierarchy of this project so that it would be helpful for a newbie.




This is a small example. In the next post, I will explain the basics and advantages of Spring MVC.
Happy coding :)

Saturday, 29 June 2013

ANT - Step By Step Build Procedure

Build Tools - Build tools are used to automate the repetitive tasks. This can be for example compiling source code, running software test and creating files and documentation for software deployment. Build tools are run from command prompt. Examples of Build tools are - Apache ANT, Maven etc.

ANT - Another Neat Tool, this is what it Stands for. Its a Java build and deployment tool written using plain XML.

Installing Apache ANT

Before starting working with ANT, you need to setup ANT in your system. Since I am using Windows operating system so I will concentrate over that only.
1. Get latest Apache ANT version from http://ant.apache.org .
2. Unzip the zip file to a location of your choice lets say C:\Ant.
3. Set up the environment variables ANT_HOME and JAVA_HOME as highlighted in the image below.















4.Now to verify whether ANT has been successfully installed or not, go to command prompt and type
   c:\>ant -versionApache
 Ant(TM) version 1.9.0 compiled on March 5 2013

 If you don't see the above output then something has gone wrong with the installation.

Step By Step creation of build.XML file. I have seggregated it into steps to have better understanding.

1. Every build.xml file starts with <project > tag. Here, default attribute will identify which target is to be    called while processing the build.xml and basedir is pointing to root directory.

<?xml version="1.0"?>
    <project name="Ant Build" basedir="." default="execute">


2. Define all the properties which would be needed. These properties will be used in the further steps. To make ANT script generic I have defined all the properties so that I can change these properties to build another java code in future. Moreover, we can have a separate build.properties files where we can define these properties as key value pair. 

 <property name="project" value="SAXParserImplementation"/>
 <property name="src.dir" value="src/parser"/>
 <property name="build.dir" value="build/class"/>
 <property name="jar.dir" value="jar"/>
 <property name="config.dir" value="config"/>
 <property name="parameters" value="D:/test.xml"/>
 <property name="jarFileName" value="SAXParser.jar"/>
 <property name="className" value="parser.SAXParserImplementation"/>
 <property name="includeFileList" value="SAXParserImplementation.java"/>

build.properties
src.dir=src/parser
build.dir=build/class


And, in the build.xml define <property file="build.properties"/>. No need to mention any other property. You can move all your properties to build.properties.

3. Our default target is execute, this target will execute the java code using java command. I have placed the test.xml inside the config folder and passed this as an argument to my java code. You can refer SAX Parser code from post.

<target name="execute" description="Executing Java Code" depends="compress">
   <echo>Executing Project - ${project}...</echo>
   <echo>Output...</echo>
   <java classpath="${build.dir}" classname="${className}">
      <arg line="${config.dir}/test.xml"/>
   </java>
</target>

But before executing it, it goes to compress target since this is dependent on it.

4. compress target will create a Jar file by using jar command and place it inside the jar.dir which I have already defined in the properties.

<target name="compress" description="Create a Jar file" depends="compile">
   <echo>Creating Jar file...</echo>
       <jar destfile="${jar.dir}/${jarFileName}" basedir="${build.dir}"/>
</target>

But before executing it, it goes to compile target.

5. compile target is used to create the class files which will take the java code from src.dir and compiled it to build.dir. The includes attribute defines which all files need to be compiled. Since in my project, number of java files were there in the folder. But I wanted to compile only SAXParserImplementation.java, so I defined it in that attribute. You can define more java classes also as a comma separated list.

<target name="compile" description="Create a class file" depends="init">
   <echo>Compiling Java file...</echo>
   <javac srcdir="${src.dir}" destdir="${build.dir}" target="1.6" debug="true" includes="${includeFileList}"/>
</target>

Again we can see that this target is dependent on init. So it will process init first.

6. init target is used to create and copy operation.

<target name="init" description="Make directory" depends="clean">
   <echo>Creating Build/Jar Directory...</echo>
   <mkdir dir="${build.dir}"/>
   <mkdir dir="${jar.dir}"/>
   <mkdir dir="${config.dir}"/>
   <copy file="${parameters}"        todir="${config.dir}"/>
</target>

But this is dependent on clean, so clean will be executed first.

7. clean target is used for deleting the directories.

<target name="clean" description="Delete Directories">
   <echo>Deleting Directories...</echo>
   <delete dir="${build.dir}"/>
   <delete dir="${jar.dir}"/>
   <delete dir="${config.dir}"/>
</target>

Now start in reverse order from 7 to 1, you can easily understand what we are doing. Summarizing all the steps - clean all the directories --> create new directories --> compile your code --> create Jar out of it --> Execute it to get the output.

<?xml version="1.0"?>
<project name="Ant Build" basedir="." default="execute">
 <!--<property file="build.properties"/>-->
 <property name="project" value="SAXParserImplementation"/>
 <property name="src.dir" value="src/parser"/>
 <property name="build.dir" value="build/class"/>
 <property name="jar.dir" value="jar"/>
 <property name="config.dir" value="config"/>
 <property name="parameters" value="D:/test.xml"/>
 <property name="jarFileName" value="SAXParser.jar"/>
 <property name="className" value="parser.SAXParserImplementation"/>
 <property name="includeFileList" value="SAXParserImplementation.java"/>
 
 <target name="clean" description="Delete Directories">
  <echo>Deleting Directories...</echo>
   <delete dir="${build.dir}"/>
   <delete dir="${jar.dir}"/>
   <delete dir="${config.dir}"/>
 </target>
 
 <target name="init" description="Make directory" depends="clean">
  <echo>Creating Build/Jar Directory...</echo>
  <mkdir dir="${build.dir}"/>
  <mkdir dir="${jar.dir}"/>
  <mkdir dir="${config.dir}"/>
  <copy file="${parameters}" todir="${config.dir}"/>
 </target>
  
 <target name="compile" description="Create a class file" depends="init">
  <echo>Compiling Java file...</echo>
  <javac srcdir="${src.dir}" destdir="${build.dir}" target="1.6" debug="true" includes="${includeFileList}"/>
 </target>
 
 <target name="compress" description="Create a Jar file" depends="compile">
  <echo>Creating Jar file...</echo>
  <jar destfile="${jar.dir}/${jarFileName}" basedir="${build.dir}"/>
 </target>
 
 <target name="execute" description="Executing Java Code" depends="compress">
  <echo>Executing Project - ${project}...</echo>
  <echo>Output...</echo>
  <java classpath="${build.dir}" classname="${className}">
   <arg line="${config.dir}/test.xml"/>
  </java>
 </target>
</project>

Running the Ant Project

Copy build.xml and build.properties file(if any) to the location from where it can target the src folder as you have defined in the properties. To run it, go to command prompt and go to the directory where you have placed build.xml. Run ant command and here you go... 


Saturday, 22 June 2013

Marshalling and Unmarshalling using JAXB

JAXB stands for Java Architecture for XML Binding. JAXB provides API to access and process a XML document. We can read or write XML files using JAXB. In this post, I am going to use JAXB annotation to convert Java Object to/ from XML file. 

Before writing this post I read about marshalling and unmarshalling and found that Marshalling and Serialization in  Java are loosely synonyms. Infact Serialization is part of Marshalling. Term Marshalling is used when we talk about passing objects to remote Objects(RMI). In Marshalling Object is serialized(Member data is Serialized) + codebase is attached. CodesBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location.

Marshalling - Convert a Java Object into an XML.

Unmarshalling - Convert an XML content into a Java Object


Class JAXBExample for Marshalling and UnMarshalling


public class JAXBExample
{
 private JAXBContext jaxbContext;

 public static void main(String args[])
 {
  JAXBExample jaxb = new JAXBExample();
  Employee employee = new Employee("1002", "Ankit", 200000, "Bangalore",
    9876);
  jaxb.convertToXML(employee);
  jaxb.convertToObject();
 }

 /**
  * Marshallling
  * 
  * @param employee
  */
 private void convertToXML(Employee employee)
 {
  try
  {
   jaxbContext = JAXBContext.newInstance(Employee.class);
   // Obtain marshaller from JaxbContext
   Marshaller marshaller = jaxbContext.createMarshaller();
   marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
   marshaller.marshal(employee, System.out);
  } catch (JAXBException e)
  {
   e.printStackTrace();
  }
 }

 /**
  * Unmarshalling
  */
 private void convertToObject()
 {
  Unmarshaller jaxbUnmarshaller;
  try
  {
   jaxbUnmarshaller = jaxbContext.createUnmarshaller();
   Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new File(
     "D:\\test.xml"));
   System.out.println("\n"+"Employee Details:");
   System.out.println("Id:" + employee.getId() + "\n" + "Name:"
     + employee.getName() + "\n" + "Salary:"
     + employee.getSalary() + "\n" + "Address:"
     + employee.getAddress() + "\n" + "Contact:"
     + employee.getContact());
  } catch (JAXBException e)
  {
   e.printStackTrace();
  }
 }
}



Annotated Class Employee




@XmlRootElement
class Employee
{
 private String id;
 private String name;
 private int salary;
 private String address;
 private int contact;

 Employee()
 {

 }

 Employee(String id, String name, int salary, String address, int contact)
 {
  this.id = id;
  this.name = name;
  this.salary = salary;
  this.address = address;
  this.contact = contact;
 }

 public String getId()
 {
  return id;
 }

 @XmlAttribute
 public void setId(String id)
 {
  this.id = id;
 }

 public String getName()
 {
  return name;
 }

 @XmlElement
 public void setName(String name)
 {
  this.name = name;
 }

 public int getSalary()
 {
  return salary;
 }

 @XmlElement
 public void setSalary(int salary)
 {
  this.salary = salary;
 }

 public String getAddress()
 {
  return address;
 }

 @XmlElement
 public void setAddress(String address)
 {
  this.address = address;
 }

 public int getContact()
 {
  return contact;
 }

 @XmlElement
 public void setContact(int contact)
 {
  this.contact = contact;
 }
}



XML



<?xml version="1.0"?>
<employee id="1002">
 <name>Ankit</name>
 <salary>200000</salary>
 <address>Bangalore</address>
 <contact>9876</contact>
</employee>


Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="1002">
    <address>Bangalore</address>
    <contact>9876</contact>
    <name>Ankit</name>
    <salary>200000</salary>
</employee>

Employee Details:
Id:1002
Name:Ankit
Salary:200000
Address:Bangalore
Contact:9876