Spring Batch Example MySQL Database To XML

A typical batch program generally reads a large number of records from a database, file, or queue, processes the data in some fashion, and then writes back data in a modified form to database,file-system, mailer etc.

Spring Batch automates this basic batch iteration, providing the capability to process similar transactions as a set, typically in an offline environment without any user interaction.

In this tutorial, we will show you how to read data from a MySQL database, with JdbcCursorItemReader and JdbcPagingItemReader, and write it into an XML file.

Tools and libraries used

  • Spring Tool Suite (STS)
  • JDK 1.6
  • Spring Core 3.2.2.RELEASE
  • Spring OXM 3.2.2.RELEASE
  • Spring Batch 2.2.0.RELEASE
  • MySQL Java Driver 5.1.25

Work flow of this Example-How it works?

Spring Batch works like read data in some chunk size[configurable] from data source, and write that chunk to some resource. Here data source for reader could be flat files[text file, xml file, csv file etc], relational database[e.g. mysql], mongodb. Similarly writer could write data read by reader to flat files, relation database, mongodb, mailer etc.

Reading, processing, writing all together is termed as Job.

Sample Example of Spring Batch MySQL Database To XML-
1. Project Directory Structure

Spring Batch Example MySQL Database To XML

2. Database
Employee table contain some data in DAVDB database.

CREATE TABLE `employeet` (
  `empid` int(11) NOT NULL AUTO_INCREMENT,
  `empaddress` varchar(255) DEFAULT NULL,
  `empAge` int(11) DEFAULT NULL,
  `empname` varchar(255) DEFAULT NULL,
  `salary` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`empid`)
) 

//Insert data from following query

INSERT INTO `DAVDB`.`employeet` 
 (`empid`, 
 `empaddress`, 
 `empAge`, 
 `empname`, 
 `salary`
 )
 VALUES
 ('empid', 
 'empaddress', 
 'empAge', 
 'empname', 
 'salary'
 );

3. Item Reader
Create a row mapper to map database values to “Employee” object.
Employee.java

package com.doj.batch.bean;

import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh Rajput
 *
 */
@XmlRootElement(name="employee")
@XmlAccessorOrder(XmlAccessOrder.UNDEFINED)
public class Employee {
 private int empid;
 private String name;
 private int age;
 private float salary;
 private String address;
 /**
  * @return the empid
  */
 public int getEmpid() {
  return empid;
 }
 /**
  * @param empid the empid to set
  */
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 /**
  * @return the name
  */
 public String getName() {
  return name;
 }
 /**
  * @param name the name to set
  */
 public void setName(String name) {
  this.name = name;
 }
 /**
  * @return the age
  */
 public int getAge() {
  return age;
 }
 /**
  * @param age the age to set
  */
 public void setAge(int age) {
  this.age = age;
 }
 /**
  * @return the salary
  */
 public float getSalary() {
  return salary;
 }
 /**
  * @param salary the salary to set
  */
 public void setSalary(float salary) {
  this.salary = salary;
 }
 /**
  * @return the address
  */
 public String getAddress() {
  return address;
 }
 /**
  * @param address the address to set
  */
 public void setAddress(String address) {
  this.address = address;
 }
}

EmployeeRowMapper.java

package com.doj.batch.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.doj.batch.bean.Employee;

/**
 * @author Dinesh Rajput
 *
 */
public class EmployeeRowMapper implements RowMapper<Employee>{

 @Override
 public Employee mapRow(ResultSet resultSet, int rowNum) throws SQLException {
  Employee employee = new Employee();
  employee.setEmpid(resultSet.getInt("empid"));
  employee.setName(resultSet.getString("empname"));
  employee.setSalary(resultSet.getLong("salary"));
  employee.setAddress(resultSet.getString("empaddress"));
  employee.setAge(resultSet.getInt("empAge"));
  return employee;
 }

}

Example to read data from database.

<bean id="itemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader" scope="step">
  <property name="dataSource" ref="dataSource"/>
  <property name="sql" value="select empid, empname, empAge, empaddress, salary from employeet" />
  <property name="rowMapper">
   <bean class="com.doj.batch.mapper.EmployeeRowMapper" />
  </property>
   </bean>

4. Item Writer
Write data to an XML file.

<bean id="itemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
  <property name="resource" value="file:xml/outputs/employees.xml" />
  <property name="marshaller" ref="empMarshaller" />
  <property name="rootTagName" value="employees" />
  </bean> 
    
    <bean id="empMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
  <property name="classesToBeBound">
   <value>com.doj.batch.bean.Employee</value>
  </property>
   </bean> 

5. Spring Batch Jobs
A job to read data from MySQL and write it XML file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:batch="http://www.springframework.org/schema/batch"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/batch 
http://www.springframework.org/schema/batch/spring-batch-2.0.xsd">

 <import resource="applicationContext.xml"/>
 <import resource="ApplicationDB.xml"/>
 
 <bean id="itemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader" scope="step">
  <property name="dataSource" ref="dataSource"/>
  <property name="sql" value="select empid, empname, empAge, empaddress, salary from employeet" />
  <property name="rowMapper">
   <bean class="com.doj.batch.mapper.EmployeeRowMapper" />
  </property>
   </bean>
 
    <bean id="itemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
  <property name="resource" value="file:xml/outputs/employees.xml" />
  <property name="marshaller" ref="empMarshaller" />
  <property name="rootTagName" value="employees" />
  </bean> 
    
    <bean id="empMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
  <property name="classesToBeBound">
   <value>com.doj.batch.bean.Employee</value>
  </property>
   </bean> 
  
    <batch:job id="simpleDojJob" job-repository="jobRepository" parent="simpleJob">
     <batch:step id="step1">
      <batch:tasklet transaction-manager="transactionManager">
       <batch:chunk reader="itemReader" writer="itemWriter" commit-interval="1"/>
      </batch:tasklet>
     </batch:step>
    </batch:job>   
</beans>

ApplicationDB.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
 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/jdbc 
  http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd">
 
        <!-- connect to database -->
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/DAVDB" />
  <property name="username" value="root" />
  <property name="password" value="root" />
 </bean>
 
 <bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
 
</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

 <bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
 
    <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <property name="jobRepository" ref="jobRepository"/>
    </bean>
 
    <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>
 
    <bean id="simpleJob" class="org.springframework.batch.core.job.SimpleJob" abstract="true">
        <property name="jobRepository" ref="jobRepository" />
    </bean>
 
</beans>

6. Launching Batch Job-
Spring Batch comes with a simple utility class called CommandLineJobRunner which has a main() method which accepts two arguments. First argument is the spring application context file containing job definition and the second is the name of the job to be executed.

Now run as a java application with both two arguments.
org.springframework.batch.core.launch.support.CommandLineJobRunner
simple-job.xml simpleDojJob

Output. Extracts all employees into an XML file.
employees.xml

<?xml version="1.0" encoding="UTF-8"?>
<employees>
 <employee>
  <address>delhi</address>
  <age>17</age>
  <empid>1</empid>
  <name>ATUL KUMAR</name>
  <salary>300000.0</salary>
 </employee>
 <employee>
  <address>delhi</address>
  <age>21</age>
  <empid>2</empid>
  <name>ASHUTOSH RAJPUT</name>
  <salary>300000.0</salary>
 </employee>
 <employee>
  <address>delhi</address>
  <age>17</age>
  <empid>3</empid>
  <name>Dinesh Rajput</name>
  <salary>300000.0</salary>
 </employee>
</employees>

Download Source Code with libs
SpringBatchDatabaseToXml.zip

Spring Batch ItemReader and ItemWriter Example

In this tutorial we will discuss about the three most important interfaces of spring batch and an overview of Spring Batch item reader and writer with a sample application. One of the important goals of a batch processing framework is to read large amounts of data, perform some business processing/transformation and write out the result. Spring Batch Framework supports this bulk reading, processing and writing using three key interfaces: ItemReader, ItemProcessor and ItemWriter.
Popular Spring Tutorials

  1. Spring Tutorial
  2. Spring MVC Web Tutorial
  3. Spring Boot Tutorial
  4. Spring JDBC Tutorial
  5. Spring AOP Tutorial
  6. Spring Security Tutorial

1. ItemReader is the means for providing data from many different types of input. ItemReader interface is the means for reading bulk data in a bulk processing system. There are many different implementations of ItemReader interface. All implementations are expected to be stateful and will be called multiple times for each batch, with each call to read() returning a different value and finally returning null when all input data is exhausted. Below are few frequently used implementations of ItemReader.

ItemReader Implementation Description
FlatFileItemReader Reads lines of data from input file. Typically read line describe records with fields of data defined by fixed positions in the file or delimited by some special character (e.g. Comma (,), Pipe (|) etc).
JdbcCursorItemReader Opens a JDBC cursor and continually retrieves the next row in the ResultSet.
StoredProcedureItemReader Executes a stored procedure and then reads the returned cursor and continually retrieves the next row in the ResultSet.

All the above implementations override the read() method from the ItemReader interface. The read method defines the most essential contract of the ItemReader. It returns one item or null if no more items are left. An item might represent a line in a file, a row in a database and so on.

2. ItemWriter is similar in functionality to an ItemReader, but with inverse operations. ItemWriter is a interface for generic output operations. Implementation class will be responsible for serializing objects as necessary. Resources still need to be located, opened and closed but they differ in that an ItemWriter writes out, rather than reading in. For databases these may be inserts or updates.

The write method defines the most essential contract of the ItemWriter. It will attempt to write out the list of items passed in as long as it is open. As it is expected that items will be ‘batched’ together into a chunk and then output, the interface accepts a list of items, rather than an item by itself. Once the items are written out , any flushing that may be necessary can be performed before returning from the write method.

ItemWriter Implementation Description
FlatFileItemWriter Writes data to a file or stream. Uses buffered writer to improve performance.
StaxEventItemWriter An implementation of ItemWriter which uses StAX and Marshaller for serializing object to XML.

3. ItemProcessor– The ItemReader and ItemWriter interfaces are both very useful for their specific tasks, but what if you want to insert business logic before writing? An ItemProcessor is very simple interface for item transformation. Given one object, transform it and return another. Any business/transformation logic can be plugged into this component. Assume an ItemReader provides a class of type User, and it needs to be converted to type Employee before being written out. An ItemProcessor can be written that performs the conversion. Another typical use for an item processor is to filter out records before they are passed to the ItemWriter. Filtering simply indicates that a record should not be written.

Create Sample Application Example-
In this sample application we will describe all three interfaces implementation.
We required following technologies

  • Spring Tool Suite (STS)
  • JDK 1.6
  • Spring Core 3.2.2.RELEASE
  • Spring Batch 2.2.0.RELEASE

Project Directory Structure-
Review the final project structure, a standard java project.

Create Custom Item Reader-
Below is our custom item reader. Each time it is called, it returns the next element from the list and returns null if the list is exhausted.

CustomItemReader.java

package com.doj.batch.reader;

import java.util.List;

import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;

/**
 * @author Dinesh Rajput
 *
 */
public class CustomItemReader implements ItemReader<String>{
 
 private List<String> bookNameList;
 private int bookCount = 0;
 @Override
 public String read() throws Exception, UnexpectedInputException,
   ParseException {
  if(bookCount < bookNameList.size()){
   return bookNameList.get(bookCount++);
  }else{
   return null;
  }
 }
 public List<String> getUserNameList() {
  return bookNameList;
 }
 public void setBookNameList(List<String> bookNameList) {
  this.bookNameList = bookNameList;
 }
 
}

Create Custom Item Processor-
CustomItemProcessor is simple custom ItemProcessor which transforms every element returned by the ItemReader. Here book name return with respective author name.

CustomItemProcessor.java

package com.doj.batch.processor;

import org.springframework.batch.item.ItemProcessor;

/**
 * @author Dinesh Rajput
 *
 */
public class CustomItemProcessor implements ItemProcessor<String, String> {

 @Override
 public String process(String bookNameWithoutAuthor) throws Exception {
  String bookNameWithAuthor = "Book Name - "+bookNameWithoutAuthor+" | Author Name - ";
  if("Effective Java".equalsIgnoreCase(bookNameWithoutAuthor)){
   bookNameWithAuthor += "Joshua Bloch";
  }else if("Design Patterns".equalsIgnoreCase(bookNameWithoutAuthor)){
   bookNameWithAuthor += "Erich Gamma";
  }else if("Refactoring".equalsIgnoreCase(bookNameWithoutAuthor)){
   bookNameWithAuthor += "Martin Fowler";
  }else if("Head First Java".equalsIgnoreCase(bookNameWithoutAuthor)){
   bookNameWithAuthor += "Kathy Sierra";
  }else if("Thinking in Java".equalsIgnoreCase(bookNameWithoutAuthor)){
   bookNameWithAuthor += " Bruce Eckel";
  }
  return bookNameWithAuthor;
 }

}

Create Custom Item Writer-
CustomItemWriter is custom ItemWriter which outputs the transformed item(s) returned by our CustomItemProcessor.

CustomItemWriter.java

package com.doj.batch.writer;

import java.util.List;

import org.springframework.batch.item.ItemWriter;

/**
 * @author Dinesh Rajput
 *
 */
public class CustomItemWriter implements ItemWriter<String> {

 @Override
 public void write(List<? extends String> bookNameWithAuthor) throws Exception {
  System.out.println(bookNameWithAuthor);
 }

}

Create Application Context XML-
Below is the applicationContext.xml which is required to create JobRepository, JobLauncher and TransactionManager.

JobRepository
Repository is responsible for persistence of batch meta-data information. SimpleJobRepository is an implementation of JobRepository that stores JobInstances, JobExecutions, and StepExecutions information using the DAOs injected via constructure arguments. Spring Batch supports two implementation of these DAOs: Map based (in-memory) and Jdbc based. In real enterprise application the Jdbc variants are preffered but we will use simpler in-memory alternatives (MapJobInstanceDao, MapJobExecutionDao, MapStepExecutionDao, MapExecutionContextDao) in this example.

JobLauncher
As name suggests it is responsible for launching batch job. We are using SimpleJobLauncher implementation which requires only one dependency, a JobRepository. JobRepository is used to obtain a valid JobExecution. Repository must be used because the provided Job could be a restart of an existing JobInstance, and only the Repository can reliably recreate it.

TransactionManager
As this example won’t be dealing with transactional data, we are using ResourcelessTransactionManager which is mainly used for testing purpose.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

 <bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
 
    <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <property name="jobRepository" ref="jobRepository"/>
    </bean>
 
    <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>
 
    <bean id="simpleJob" class="org.springframework.batch.core.job.SimpleJob" abstract="true">
        <property name="jobRepository" ref="jobRepository" />
    </bean>
 
</beans>

Create Job configuration XML-
It’s time to wire the above 3 components together into a job which will perform reading, processing and transformation work for us.
simple-job.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:batch="http://www.springframework.org/schema/batch"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/batch 
http://www.springframework.org/schema/batch/spring-batch-2.0.xsd">

 <import resource="applicationContext.xml"/>
 
 <bean id="customReader" class="com.doj.batch.reader.CustomItemReader" >
        <property name="bookNameList" >
            <list>
                <value>Effective Java</value>
                <value>Design Patterns</value>
                <value>Refactoring</value>
                <value>Thinking in Java</value>
                <value>Head First Java</value>
            </list>
        </property>
    </bean>
 
    <bean id="customProcessor" class="com.doj.batch.processor.CustomItemProcessor" />
 
    <bean id="customWriter" class="com.doj.batch.writer.CustomItemWriter" /> 
    
    <batch:job id="simpleDojJob" job-repository="jobRepository" parent="simpleJob">
     <batch:step id="step1">
      <batch:tasklet transaction-manager="transactionManager">
       <batch:chunk reader="customReader" processor="customProcessor" writer="customWriter" commit-interval="1"/>
      </batch:tasklet>
     </batch:step>
    </batch:job>   
</beans>

First we create three beans (customReader, customWriter, customProcessor) corresponding to CustomItemReader, CustomItemWriter and CustomItemProcessor. Note that the customReader is injected with the list of book names. This list is the source of data for the customReader bean.

Later we created a simpleStep bean using the SimpleStepFactoryBean class. Most common configuration options for simple steps should be found in this factory class. We injected the jobRepository, transactionManager, customReader, customWriter and customProcessor in this simple step bean. Note the property commitInterval which is set to 1. This tells Spring Batch that the commit should happen after 1 element .i.e. writer will write 1 item at a time.

Launching Batch Job-
Spring Batch comes with a simple utility class called CommandLineJobRunner which has a main() method which accepts two arguments. First argument is the spring application context file containing job definition and the second is the name of the job to be executed.

Now run as a java application with both two arguments.
org.springframework.batch.core.launch.support.CommandLineJobRunner
simple-job.xml simpleDojJob 

Following output-
[Book Name – Effective Java | Author Name – Joshua Bloch]
[Book Name – Design Patterns | Author Name – Erich Gamma]
[Book Name – Refactoring | Author Name – Martin Fowler]
[Book Name – Thinking in Java | Author Name – Bruce Eckel]
[Book Name – Head First Java | Author Name – Kathy Sierra]

Download Source Code with Libs
SpringBatchReaderWriterExample.zip

JAXB Unmarshalling Example

By the help of UnMarshaller interface, we can unmarshal(read) the object into xml document.

In this example, we are going to convert simple xml document into java object.

Let’s see the steps to convert XML document into java object.

  1. Create POJO or bind the schema and generate the classes
  2. Create the JAXBContext object
  3. Create the Unmarshaller objects
  4. Call the unmarshal method
  5. Use getter methods of POJO to access the data

Unmarshaller example: Converting xml document into java object

Xml Document(employee.xml)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee empid="1111">
    <address>
        <city>Noida</city>
        <locality>Sector-88</locality>
        <pin>201301</pin>
    </address>
    <address>
        <city>Kannauj</city>
        <locality>Kamala Nagar</locality>
        <pin>209724</pin>
    </address>
    <name>Dinesh Rajput</name>
    <salary>100000.0</salary>
</employee>

Employee.java

package com.doj.jaxb;

import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh Rajput
 *
 */
@XmlRootElement
public class Employee {
 private int empid;  
    private String name;  
    private float salary;
    private List<Address> address;
 
    @XmlAttribute  
    public int getEmpid() {
  return empid;
 }
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 @XmlElement  
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @XmlElement  
 public float getSalary() {
  return salary;
 }
 public void setSalary(float salary) {
  this.salary = salary;
 }
 @XmlElement  
 public List<Address> getAddress() {
  return address;
 }
 public void setAddress(List<Address> address) {
  this.address = address;
 }
    
}

Address.java

package com.doj.jaxb;

/**
 * @author Dinesh Rajput
 *
 */
public class Address {
 private String locality;
 private String city;
 private int pin;
 
 public String getLocality() {
  return locality;
 }
 public void setLocality(String locality) {
  this.locality = locality;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public int getPin() {
  return pin;
 }
 public void setPin(int pin) {
  this.pin = pin;
 }
}

JaxbUnmarshalTest.java

package com.doj.jaxb;
import java.io.File;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * @author Dinesh Rajput
 *
 */
public class JaxbUnmarshalTest {

 /**
  * @param args
  * @throws JAXBException 
  */
 public static void main(String[] args) throws JAXBException {
  File file = new File("employee.xml");  
        JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);  
   
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();  
        Employee emp = (Employee) jaxbUnmarshaller.unmarshal(file);  
          
        System.out.println("Employee-"+emp.getEmpid()+" | "+emp.getName()+" | "+emp.getSalary());  
        System.out.println("Addresses: ");  
        List<Address> list = emp.getAddress();  
        for(Address address : list){  
         System.out.println(address.getLocality()+" | "+address.getCity()+" | "+address.getPin());
        }
 }
}

Run this application you get following output-
Employee-1111 | Dinesh Rajput | 100000.0
Addresses:
Sector-88 | Noida | 201301
Kamala Nagar | Kannauj | 209724

JAXB Unmarshalling Example

Download Source Code
JaxBUnmarshalExample.zip

<<Previous <<   || Index ||   >>Next >>

JAXB Marshalling Example

In this tutorial we are using Marshaller interface, we can marshal(write) the object into xml document. In the previous page, we have seen the simple example of converting object into xml.

In this example, we are going to convert the object into xml having primitives, strings and collection objects.

Let’s see the steps to convert java object into XML document.

  1. Create POJO or bind the schema and generate the classes
  2. Create the JAXBContext object
  3. Create the Marshaller objects
  4. Create the content tree by using set methods
  5. Call the marshal method

Employee.java

package com.doj.jaxb;

import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh Rajput
 *
 */
@XmlRootElement
public class Employee {
 private int empid;  
    private String name;  
    private float salary;
    private List<Address> address;
 
    @XmlAttribute  
    public int getEmpid() {
  return empid;
 }
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 @XmlElement  
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @XmlElement  
 public float getSalary() {
  return salary;
 }
 public void setSalary(float salary) {
  this.salary = salary;
 }
 @XmlElement  
 public List<Address> getAddress() {
  return address;
 }
 public void setAddress(List<Address> address) {
  this.address = address;
 }
    
}

Address.java

package com.doj.jaxb;

/**
 * @author Dinesh Rajput
 *
 */
public class Address {
 private String locality;
 private String city;
 private int pin;
 
 public String getLocality() {
  return locality;
 }
 public void setLocality(String locality) {
  this.locality = locality;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public int getPin() {
  return pin;
 }
 public void setPin(int pin) {
  this.pin = pin;
 }
}

JaxBMarshalTest.java

package com.doj.jaxb;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 * @author Dinesh Rajput
 *
 */
public class JaxBMarshalTest {

 /**
  * @param args
  * @throws JAXBException 
  * @throws FileNotFoundException 
  */
 public static void main(String[] args) throws JAXBException, FileNotFoundException {
  JAXBContext contextObj = JAXBContext.newInstance(Employee.class);  
    
     Marshaller marshallerObj = contextObj.createMarshaller();  
     marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
   
     Address localAddress = new Address();
     localAddress.setLocality("Sector-88");
     localAddress.setCity("Noida");
     localAddress.setPin(201301);
     
     Address permanentAddress = new Address();  
     permanentAddress.setLocality("Kamala Nagar");
     permanentAddress.setCity("Kannauj");
     permanentAddress.setPin(209724);
     
     List<Address> list=new ArrayList<Address>();  
     list.add(localAddress);  
     list.add(permanentAddress);  
       
     Employee emp = new Employee();
     emp.setEmpid(1111);
     emp.setName("Dinesh Rajput");
     emp.setSalary(100000);
     emp.setAddress(list);
     
     marshallerObj.marshal(emp, new FileOutputStream("employee.xml"));  
 }

}

Now run this application we get the following employee.xml file.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee empid="1111">
    <address>
        <city>Noida</city>
        <locality>Sector-88</locality>
        <pin>201301</pin>
    </address>
    <address>
        <city>Kannauj</city>
        <locality>Kamala Nagar</locality>
        <pin>209724</pin>
    </address>
    <name>Dinesh Rajput</name>
    <salary>100000.0</salary>
</employee>

JAXB Marshalling Example

Download Source Code
JaxBMarshalExample.zip

<<Previous <<   || Index ||   >>Next >>

JAXB Hello World Example

JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs :

  • Marshalling – Convert a Java object into a XML file.
  • Unmarshalling – Convert XML content into a Java Object.

Technologies used in this article

  • JDK 1.6
  • JAXB 2.2.7

Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.

Simple JAXB Marshalling Example: Converting Object into XML

Let’s see the steps to convert java object into XML document.

  1. Create POJO or bind the schema and generate the classes
  2. Create the JAXBContext object
  3. Create the Marshaller objects
  4. Create the content tree by using set methods
  5. Call the marshal method

Employee.java

package com.doj.jaxb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh Rajput
 *
 */
@XmlRootElement
public class Employee {
 private int empid;  
    private String name;  
    private float salary;
    private String address;
 
    @XmlAttribute  
    public int getEmpid() {
  return empid;
 }
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 @XmlElement  
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @XmlElement  
 public float getSalary() {
  return salary;
 }
 public void setSalary(float salary) {
  this.salary = salary;
 }
 @XmlElement  
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
    
    
}

  • @XmlRootElement specifies the root element for the xml document.
  • @XmlAttribute specifies the attribute for the root element.
  • @XmlElement specifies the sub element for the root element.

package com.doj.jaxb;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 * @author Dinesh Rajput
 *
 */
public class ObjectToXMLTest {

 /**
  * @param args
  * @throws JAXBException 
  * @throws FileNotFoundException 
  */
 public static void main(String[] args) throws JAXBException, FileNotFoundException {
  JAXBContext contextObj = JAXBContext.newInstance(Employee.class);  
    
     Marshaller marshallerObj = contextObj.createMarshaller();  
     marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
     Employee emp = new Employee();
     emp.setEmpid(1111);
     emp.setName("Dinesh Rajput");
     emp.setSalary(100000);
     emp.setAddress("Noida");
     
     marshallerObj.marshal(emp, new FileOutputStream("employee.xml"));  
 }

}

Run this application as java program lets see following output file in application
employee.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee empid="1111">
    <address>Noida</address>
    <name>Dinesh Rajput</name>
    <salary>100000.0</salary>
</employee>

JAXB Hello World Example

Download Source Code with libs
JaxBExample.zip

<<Previous <<   || Index ||   >>Next >>

JAXB 2X Tutorial

JAXB 2X Tutorial

JAXB stands for Java Architecture for XML Binding. It provides mechanism to marshal (write) java objects into XML and unmarshal (read) XML into object. Simply, you can say it is used to convert java object into xml and vice-versa. It constitutes a convenient framework for processing XML documents, providing significant benefits as compared to previously available methods such as the one following the Document Object Model (DOM).

JAXB 2X


What is new in JAXB 2.x?
JAXB 2.x includes several features that were not present in JAXB 1.x. They are as follows:

1) Annotation support: JAXB 2.x provides support to annotation so less coding is required to develop JAXB application. The javax.xml.bind.annotation package provides classes and interfaces for JAXB 2.x.

2) Support for all W3C XML Schema features: it supports all the W3C schema unlike JAXB 1.0.

3) Additional Validation Capabilities: it provides additional validation support by JAXP 1.3 validation API.

4) Small Runtime Library: it required small runtime library that JAXB 1.0.

5) Reduction of generated schema-derived classes: it reduces a lot of generated schema-derived classes.

Unmarshalling an XML document with the appropriate JAXB method also results in a tree of objects, with the significant difference being that the nodes in this tree correspond to XML elements, which contain attributes and the content as instance variables and refer to child elements by object references.

Schemas written in the XML Schema Language can describe structural relationships and data types, with a very high level of distinctiveness. The scalar datatypes of the XML Schema Language are mapped to Java data types. Lists of values and certain element groupings are mapped to Java’s java.util.List. It should be noted that the XML Schema language is capable of defining XML structures that cannot be bound by a schema compiler. In many of these cases it is possible to circumnavigate the problem by adding binding declarations to direct the schema compiler in some specific way to achieve a successful binding.

JAXB 2 – Java Architecture for XML Binding

JAXB uses annotations to indicate the central elements.
Annotation Description
@XmlRootElement(namespace = “namespace”) Define the root element for an XML tree
@XmlType(propOrder = { “field2”, “field1”,.. }) Allows to define the order in which the fields are written in the XML file
@XmlElement(name = “neuName”) Define the XML element which will be used. Only need to be used if the neuNeu is different then the JavaBeans Name

Contents for JAXB

References
1. https://jaxb.java.net/

@ControllerAdvice annotation improvements in Spring 4

@ControllerAdvice annotation improvements in Spring 4


@ControllerAdvice is introduced from the Spring 3.2 release. In this version 3.2 It is special type of @Component to declare the global exceptions handler. When you create a class with @ControllerAdvice and then write few methods with the @ExceptionHandler annotations, any exception thrown in the application will be handled by this class. It is acting as the global exception handler. However, you can not restrict this handling to any specific type of controller or classes.

Among many new features in Spring 4 I found @ControllerAdvice improvements. @ControllerAdvice is a specialization of a @Component that is used to define @ExceptionHandler, @InitBinder, and @ModelAttribute methods that apply to all @RequestMapping methods. Prior to Spring 4, @ControllerAdvice assisted all controllers in the same Dispatcher Servlet. With Spring 4 it has changed. As of Spring 4 @ControllerAdvice may be configured to support defined subset of controllers, whereas the default behavior can be still utilized.

By using @ControllerAdvice annotation in spring 4.0 you can narrow the scope of the exception handler. For example, you can declare a exception handler which will handle only the exception thrown by the @RestController , a special type of controller introduced in the Spring 4.0.

@ControllerAdvice assisting all controllers
Let’s assume we want to create an error handler that will print application errors to the user. Let’s assume this is a basic Spring MVC application with jsp as a view engine and we have an ArticleController with the following @RequestMapping method:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
@RequestMapping("article")
class ArticleController {
 
    @RequestMapping("{articleId}")
    @ResponseBody
    String getArticle(@PathVariable Long articleId) {
        throw new IllegalArgumentException("Getting article problem.");
    }
}

Create RestConroller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
 
@RestConroller
@RequestMapping("article")
class ArticleController {
 
    @RequestMapping("{articleId}")
    String getArticle(@PathVariable Long articleId) {
        throw new IllegalArgumentException("Getting article problem.");
    }
}

@ControllerAdvice for RestController

If you look at the below code, this exception handler called only when the exception is thrown from the RestController.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
 
@ControllerAdvice(annotations=RestController.class)
@RequestMapping("article")
class ArticleController {
    @ExceptionHandler(Exception.class)
    @RequestMapping("{articleId}")
    String getArticle(@PathVariable Long articleId) {
        throw new IllegalArgumentException("Getting article problem.");
    }
}

<<Previous <<   || Index ||   >>Next >>

Spring 4 @Conditional Annotation

As part of my series on the new features in Spring Framework, version 4, I’d like to present how to use the new Condition interface and @Conditional annotation.

@Conditional annotation-Spring 4 is introducing a new feature called Conditional – So it’s time to implement Spring 4 Conditional checking by using @Conditional annotation. This annotation with programmatic condition implementation. It can react to rich context. @Profile annotation support now simply a ProfileCondition implementation class of conditional annotation.

Spring 4 @Conditional Annotation

@ImageSource-Slideshare.net

There are times when you would like the creation and dependency injection of a bean to depend on circumstances. Those circumstance could be what operating system your application is running in, or what application server it finds itself on. Bean configuration may also depend on what version of Java is available, the value of a system property/environmental variable, or whether your application is running in dev, test, stage, or production. For these and a host of other reasons, you may want to conditionalize the instantiation and wiring of your Spring beans.

@Retention(value=RUNTIME)
@Target(value={TYPE,METHOD})
public @interface Conditional

Indicates that a component is is only eligible for registration when all specified conditions match.
A condition is any state that can be determined pro-grammatically immediately before the bean is due to be created

The @Conditional annotation may be used in any of the following ways:

  • as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes.
  • as a meta-annotation, for the purpose of composing custom stereotype annotations.
  • as a method-level annotation on any @Bean method

If a @Configuration class is marked with @Conditional, all of the @Bean methods and @Import annotations associated with that class will be subject to the conditions.

The condition interface is as follows:

public interface Condition{
/** Determine if the condition matches.
* @param context the condition context
* @param metadata meta-data of the {@link AnnotationMetadata class} or
* {@link Method method} being checked.
* @return {@code true} if the condition matches and the component can be registered
* or {@code false} to veto registration.
*/
boolean matches(ConditionContext context, AnnotatedTypeMedata metadata);
}

SPRING 4.0 CONDITIONAL BEAN CONFIGURATION-
Spring 4 adds a new @Conditional annotation that allows for a similar conditionalized configuration, but one that does not require a profile. Using the operating system example again, you would need to create two classes that implement the Spring Condition interface. This interface requires the implementation of a matches( ) method. The matches( ) method checks for a condition and returns a boolean indicating whether that condition is met.

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
 
public class LinuxCondition implements Condition{
 
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    return context.getEnvironment().getProperty("os.name").contains("Linux");  }
}
import org.springframework.context.annotation.Condition; 
import org.springframework.context.annotation.ConditionContext; 
import org.springframework.core.type.AnnotatedTypeMetadata; 
 
public class WindowsCondition implements Condition{
 
  @Override 
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    return context.getEnvironment().getProperty("os.name").contains("Windows");
  }
}

The ConditionContext parameter to matches( ) provides access to the environment, container, class loader, etc. that the condition may use to make its boolean-producing determination. The AnnotatedTypeMetadata parameter to matches( ) provides access to the method on which the @Conditional using the Condition is applied to.

With the conditions in place, now annotate your Configuration bean methods with @Conditional and the condition checking class as a parameter. Note how both methods in the Configuration return an EmailService implementation named “emailerService”. However, only one of these methods will get called by the container and create the emailerService based on the conditions provided through @Conditional.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyConfiguration {
 
  @Bean(name="emailerService")
  @Conditional(WindowsCondition.class)
  public EmailService windowsEmailerService(){
      return new WindowsEmailService();
  }
 
  @Bean(name="emailerService")
  @Conditional(LinuxCondition.class)
  public EmailService linuxEmailerService(){
    return new LinuxEmailService();
  }
}

The example here uses the conditions for the creation of just one bean. However, the conditions serve as a more reusable mechanism, which could be used to conditionalize all sorts of beans.

<<Previous <<   || Index ||   >>Next >>

RestController in Spring 4 MVC Framework

One of the new features of API improvements is new @RestController annotation which is inherited from the @Controller annotation.

Prior to the version 4.0, all the Spring MVC components has to use the common @Controller annotation to mark that as the controller servlet. When you implement a RESTful web services, the response would be always sent with the response body. To make this simple, Spring 4.0 has provided a specialized version of controller. Look at the definition of the @RestController implementation.

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Controller
 @ResponseBody
public @interface RestController

A convenience annotation that is itself annotated with @Controller and @ResponseBody.

Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

It’s a very common use case to have Controllers implement a REST API, thus serving only JSON, XML or custom MediaType content. For convenience, instead of annotating all your @RequestMapping methods with @ResponseBody, you can annotate your Controller Class with @RestController.

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

1. Download Spring MVC 4.0 jar files from this maven repository here.

2. Create Dynamic Web Project and add the libraries you downloaded to WEB-INF/lib folder.

RestController in Spring 4 MVC Framework

3. Open /WEB-INF/web.xml file and add below configuration.

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Spring4RestController</display-name>
  
 <servlet>  
  <servlet-name>spring4</servlet-name>  
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  <load-on-startup>1</load-on-startup>  
 </servlet>  
 <servlet-mapping>  
  <servlet-name>spring4</servlet-name>  
  <url-pattern>/*</url-pattern>  
 </servlet-mapping> 
</web-app>

Note that in the above code,we have named Spring Dispatcher servlet class as “spring4” and the url pattern is given as “/*” which means any uri with the root of this web application will call DispatcherServlet. DispatcherServlet will look for configuration files following this naming convention – [servlet-name]-servlet.xml. In this example, I have named dispatcher servlet class as “spring4” and hence it will look for file named ‘spring4-servlet.xml’.

4. Now create an xml file under WEB-INF folder and name it ‘spring4-servlet.xml‘.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

 <context:component-scan base-package="com.doj.spring4.controller" />

 <mvc:annotation-driven />
 
</beans>

With ComponentScan tag, Spring auto scans all elements in the provided base package and all its child packages for Controller servlet. Also, we have used <mvc:annotation-driven> tag instead of ViewResolver, with which we can directly send response data from the controller.

5. Let us create a controller servlet in the package mentioned in the component-scan tag.
SpringRestController.java

package com.doj.spring4.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Dinesh Rajput
 *
 */
@RestController
@RequestMapping("/service/greeting")
public class SpringRestController {
 @RequestMapping(value = "/{name}", method = RequestMethod.GET)
 public String sayHello(@PathVariable String name) {
  String result="Hello "+name+" to dineshonjava.com!!!";  
  return result;
 }
}

@RequestMapping’ annotation is used for defining incoming request urls for class and method levels. In this case all uri’s in the format <root-url>/service/greeting/ will be routed to this Controller class. With @RequestMapping annotation, we can only define generic uri mappings. For dynamic uri mappings in case of passing variables along with the uri, @PathVariable is used. Here in this case, we pass a variable ‘name’ along with the uri such as, <root-url>/service/greeting/Dinesh. Here the last parameter Dinesh in the uri is retrieved using @PathVariable.

I explained that while using <mvc:annotation-config> tag instead of view resolver, we use ‘@ResponseBody’ annotation to return response data directly from controller. But in the above code, I have not used ‘@ResponseBody’. This is because, in Spring MVC 4.0, they have introduced ‘@RestController’ such that we need not use ‘@ResponseBody’ tag in each and every method. ‘@RestController’ will handle all of that at the type level.

This annotation simplifies the controller and it has ‘@Controller’ and ‘@ResponseBody’ annotated within itself.

Let us take a look at the same controller but with Spring MVC 3.0,

@Controller
@RequestMapping("/service/greeting")
public class SpringRestController {
 @RequestMapping(value = "/{name}", method = RequestMethod.GET)
 public @ResponseBody String sayHello(@PathVariable String name) {
  String result="Hello "+name+" to dineshonjava.com!!!";  
  return result;
 }
}

Note that in Spring MVC 3.0 we had to explicitly use @Controller annotation to specify controller servlet and @ResponseBody annotation in each and every method. With the introduction of ‘@RestController’ annotation in Spring MVC 4.0, we can use it in place of @Controller and @ResponseBody annotation.

So now run this application in Apache Tomcat Web Server.

http://localhost:8080/Spring4RestController/service/greeting/Dinesh

RestController in Spring 4 MVC Framework Example

Download Source Code with Libs
Spring4RestController.zip

<<Previous <<   || Index ||   >>Next >>

Spring 4 Framework Hello World Example

In this tutorial you will learn how to develop a Spring 4 Framework Hello world example. We hope this tutorial will give you a quick start with Spring MVC development using the latest Spring 4 Release.

Here first I downloaded the new release of Spring 4 Framework from here. I have created a simple hello world application using spring 4 mvc. In this particular blog I will explain you guys how to create a simple helloworld application in spring using spring 4 libraries.

Technologies Required:

  • Spring 4.0.1.RELEASE
  • JDK 1.6
  • Tomcat 7.0
  • Eclipse or STS

Project Structure
Before we start adding some controller code lets first take a look at overall project structure in eclipse. Here one thing to note down is that we never needs to add all jar files in spring distribution. I have added only necessary jars here.

Spring 4 Framework Hello World Example

web.xml
Every web project in java starts with an web.xml file, this is an entry point for application. As we starts the application or deploy the application on server the container searches for an web.xml file and work according to configurations.

There is nothing new in spring 4.0 regarding web.xml file, we need to register the DispatcherServlet here to tell the container that all other upcoming requests are going to be handled by spring itself. From now whenever a request will come to container it will delegate the control to spring configuration file to be processed accordingly.

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Spring4HelloWorld</display-name>
  <display-name>Spring4MVC</display-name>  
 <welcome-file-list>  
  <welcome-file>index.jsp</welcome-file>  
 </welcome-file-list>  
  
 <servlet>  
  <servlet-name>spring4</servlet-name>  
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  <load-on-startup>1</load-on-startup>  
 </servlet>  
 <servlet-mapping>  
  <servlet-name>spring4</servlet-name>  
  <url-pattern>*.html</url-pattern>  
 </servlet-mapping>  
</web-app>

index.jsp
We have declared an welcome file in web.xml, this is the first file that the user will see at running project. We have added a simple link here this will call the controller mappings accordingly.

<html>
<head>
 <title>dineshonjava.com | Hello Spring 4 World</title>
</head>
<body>
 <center>
 <h2>dineshonjava.com | Hello Spring 4 World</h2>
 <h4><a href="hello.html">Click Here</a></h4>
 </center>
</body>
</html>

spring4-servlet.xml
This is core of all spring applications, all configurations related to spring goes here in a single file. Here one thing to note down is that the container will detect a file as spring configuration file if the file is ending with ‘-servlet’ suffix. We have defined a base package over here that helps the application to search appropriate ‘url mapping’. Every requested url will be searched in the controller classes defined under ‘base-package’ directory and annotated with ‘@Controller’.

Spring supports a number of view types including, jsp,html,xslt,xml,freemarker etc. We have added a simple view resolved to point our jsp file to be shown as output.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"  
 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="com.doj.spring4.controller" />

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

HelloSpring4Controller.java

package com.doj.spring4.controller;

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

/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class HelloSpring4Controller {
 
 @RequestMapping("/hello")  
  public ModelAndView sayHello() {  
   String message = "Welcome to Spring 4.0 !!! dineshonjava.com";  
   return new ModelAndView("hello", "message", message);  
  }  
}

This is a simple controller class for our application, to make a class work as controller we need to add a ‘@Controller’ annotation. To match the appropriate url with controller method add a ‘@RequestMapping’ annotation there enclosed within double cotes.

hello.jsp

<html>
<head>
 <title>dineshonjava.com | Hello Spring 4 World</title>
</head>
<body>
 <center>
  <h2>dineshonjava.com | Hello Spring 4 World</h2>
  <h4>${message}</h4>
 </center>
</body>
</html>

We can generate a War file and deploy that to a web server to test the application. In eclipse , right click the project and Click Run As web application at tomcat server. This will build the project and create a war file in the target folder. In the case of this example the file will be Spring4HelloWorld.war

Deploy this WAR file to a web server , say Tomcat and issue.

http://localhost:8080/Spring4HelloWorld/

Spring 4 Hello World Example

http://localhost:8080/Spring4HelloWorld/hello.html

Hello World Example in Spring 4

Download Source Code with Libs
Spring4HelloWorld.zip

<<Previous <<   || Index ||   >>Next >>