Thursday, July 17, 2008

AJAX and JSON

If we are using AJAX calls in our web pages it is difficult to process the response, which is coming from the server in xml format. Also it is difficult to create the response in xml format. One solution for this problem is the use of JSON format of communication between the client and server when we are using AJAX calls.

Before going to see the example we can see what is JSON format?

What is JSON format?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

For more information please visit

http://json-lib.sourceforge.net/index.html
http://www.json.org/java/

JAR files required:
commons-beanutils.jar
commons-collections-3.2.1.jar
commons-lang-2.4.jar
ezmorph-1.0.4.jar
json-lib-2.2.2-jdk15.jar
servlet-api.jar

Here we are going to implement an employee search web application. We have a list of employees, each of them have the properties name, employee id and department. For the time being this information are kept in a java List object.
Now in our application the user will be able to select one department and click on search. Then the lists of employees associated with the department are got listed in the table.
























Response in JSON format:[{"department":"HR","employeeId":"1002","name":"John"},{"department":"HR","employeeId":"1003","name":"Albert"},{"department":"HR","employeeId":"1008","name":"Thomas"}]


Employee class is given below.




EmployeeSearchBO class will initialize the list of Employee objects inside the static block.
findEmployeeByDepartment() will accept the department name as argument and will return the list of Employee objects belongs to that department.




We are separating the JSP and JS codes in separate files. EmployeeSearch.jsp will accept the department name for search.




EmployeeSearch.js will contain the methods to call the server using AJAX. It will send the department name as the search parameter to the server. From the server we will get the list of Employee objects in the format of JSON. The response will contain array of Employee objects. So we can iterate through the list and we can get each Employee object.




The servlet EmployeeSearchController will call the EmployeeSearchBO. findEmployeeByDepartment() to get the list of Employee objects. We are using JSONSearializer to convert the list object into JSON format. After that we are writing the same to response.




web.xml




Friday, June 20, 2008

Spring DAO with JdbcDaoSupport

This example performs the database operations insert/delete/select/update on the table named Person using Spring JdbcDaoSupport.

Database: MySQL

Table Structure:

Field

Type

Null

Key

Default

Extra

id

varchar(20)

NO

PRI



name

varchar(50)

YES


(NULL)


age

int(11)

YES


(NULL)


place

varchar(50)

YES


(NULL)


Jar files those should be present in classpath

spring-jdbc.jar

spring.jar

commons-logging.jar

mysql-connector-java-5.0.4-bin.jar

Java files

Person.java

Bean, which holds the person information.

PersonDao.java

Interface, which contains the base methods for database operations.

PersonDaoImpl.java

Implements the interface PersonDao and extends JdbcDaoSupport.

The DataSource object is injected to this bean from PersonDao.xml.

PersonBO.java

From this class the dao methods are invoked.

PersonDao.xml

This contains the bean definitions required for dao call.




package rhymes.springdao.bean;

public class Person {
private String id;
private String name;
private Integer age;
private String place;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String toString(){
StringBuffer person = new StringBuffer();
person.append("\nId " + id);
person.append("\nName " + name);
person.append("\nPlace " + place);
person.append("\nAge " + age);
return person.toString();
}
}



package rhymes.springdao;


import java.util.List;

import rhymes.springdao.bean.Person;

public interface PersonDao{
public int insert(Person person);
public int update(Person person);
public int delete(Person person);
public Person findByPrimaryKey(String id);
public List get();
}


package rhymes.springdao.impl;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import rhymes.springdao.PersonDao;
import rhymes.springdao.bean.Person;

public class PersonDaoImpl extends JdbcDaoSupport implements PersonDao{

public int delete(Person person) {
String sql = "delete from Person where id = ?";
Object[] args = {person.getId()};
int status=this.getJdbcTemplate().update(sql, args);
return status;
}

public Person findByPrimaryKey(String id) {
String sql = "select id,name,age,place from Person where id = ?";
Object[] args = {id};
List personList = this.getJdbcTemplate().query(sql, args, new ParameterizedRowMapper<Person>(){
public Person mapRow(ResultSet rs, int rowNum)
throws SQLException {
Person person = new Person();
person.setAge(rs.getInt("age"));
person.setId(rs.getString("id"));
person.setName(rs.getString("name"));
person.setPlace(rs.getString("place"));
return person;
}
});
Person person = null;
for(int i=0;i<personList.size();i++){
person=(Person)personList.get(i);
}
return person;
}

public int insert(Person person) {
String sql = "insert into Person (id,name,age,place) values(?,?,?,?)";
Object[] args = {person.getId(),person.getName(),person.getAge(),person.getPlace()};
int status=this.getJdbcTemplate().update(sql, args);
return status;
}

public int update(Person person) {
String sql = "update Person set name= ?,age= ?,place= ? where id = ?";
Object[] args = {person.getName(),person.getAge(),person.getPlace(),person.getId()};
int status=this.getJdbcTemplate().update(sql, args);
return status;
}

public List get() {
String sql = "select id,name,age,place from Person";
List personList = this.getJdbcTemplate().query(sql, new ParameterizedRowMapper<Person>(){
public Person mapRow(ResultSet rs, int rowNum)
throws SQLException {
Person person = new Person();
person.setAge(rs.getInt("age"));
person.setId(rs.getString("id"));
person.setName(rs.getString("name"));
person.setPlace(rs.getString("place"));
return person;
}
});
return personList;
}
}


package rhymes.springbo;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import rhymes.springdao.PersonDao;
import rhymes.springdao.bean.Person;

public class PersonBO {
private PersonDao personDao;
public static void main(String[] args) throws NumberFormatException, IOException {
PersonBO personBO = new PersonBO();
BeanFactory BeanFactory = new ClassPathXmlApplicationContext("PersonDao.xml");
personBO.setPersonDao((PersonDao)BeanFactory.getBean("personDao"));
//personBO.insert();
//personBO.update();
//personBO.find();
//personBO.get();
//personBO.delete();
}

public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void insert(){
Person person = new Person();
person.setAge(new Integer(26));
person.setId("4");
person.setName("Suraj");
person.setPlace("Kochi");
int status = personDao.insert(person);
System.out.println("Status: " +status);
}
public void delete() {
Person person = new Person();
person.setId("3");
int status = personDao.delete(person);
System.out.println("Status: " +status);
}
public void update(){
Person person = new Person();
person.setAge(new Integer(28));
person.setId("3");
person.setName("Sandeep");
person.setPlace("jaipur");
int status = personDao.update(person);
System.out.println("Status: " +status);
}
public void find() {
Person person=personDao.findByPrimaryKey("3");
System.out.println(person);
}
public void get() {
List<Person> personList = personDao.get();
for(int i=0;i<personList.size();i++){
Person person=(Person)personList.get(i);
System.out.println(person);
}
}
}



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean id="personDao" class="rhymes.springdao.impl.PersonDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/person"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
</beans>



Tuesday, June 17, 2008

How to use SimpleDateFormat?

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800



package rhymes.dateformat;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatExample {

/**
* @param args
*/
public static void main(String[] args) {
String format[] = { "yyyy.MM.dd G 'at' HH:mm:ss z",
"MM/dd/yyyy hh:mm:ss a z", "MM/dd/yyyy kk:mm:ss z",
"EEE, MMM d, ''yy", "h:mm a", "hh 'o''clock' a, zzzz",
"K:mm a, z", "yyyyy.MMMMM.dd GGG hh:mm aaa",
"EEE, d MMM yyyy HH:mm:ss Z", "yyMMddHHmmssZ" };
Date today = new Date();
for (int i = 0; i lt; format.length; i++) {
SimpleDateFormat formatter = new SimpleDateFormat(format[i]);
System.out.println("\"" + format[i] + "\" : "
+ formatter.format(today));
}
}

}






5:45 PM





"yyyy.MM.dd G 'at' HH:mm:ss z" 2008.06.17 AD at 17:45:18 IST
"MM/dd/yyyy hh:mm:ss a z" 06/17/2008 05:45:18 PM IST
"MM/dd/yyyy kk:mm:ss z" 06/17/2008 17:45:18 IST
"EEE, MMM d, ''yy" Tue, Jun 17, '08
"h:mm a"
"hh 'o''clock' a, zzzz" 05 o'clock PM, India Standard Time
"K:mm a, z" 5:45 PM, IST
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02008.June.17 AD 05:45 PM
"EEE, d MMM yyyy HH:mm:ss Z" Tue, 17 Jun 2008 17:45:18 +0530
"yyMMddHHmmssZ" 080617174518+0530