May 2012 Posts

Calling Java Serialized Object from JSP

This article is an answer for my simple assignment i created several weeks ago for my friend, Zainul Iman. Its about creating a simple web application that can persist and retrieve values by putting it values on a java object and serialized it on a plain text file.

Okay, so basically i only create 4 files. Only 1 java files, 2 jsp and 1 servlet. And only adding several lines on web.xml file.
First is a simple java bean to store my inserted value,

package com.edw.bean;


public class Student implements Serializable{    
    private String name;
    public String getName() {
        return name;
    public void setName(String name) { = name;

And a simple jsp file to serve as view layer, in here user can insert value which will be persist on java bean.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert Value</title>
        <form method="post" action="StudentServlet">
                <td>Insert Name : </td>
                <td><input type="text" name="name" /> </td>
                <td colspan="2"><input type="submit" /></td>                

This is my servlet class, in this class i handle the serialization of the inserted value into java object

package com.edw.servlet;

import com.edw.bean.Student;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StudentServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        Student student = new Student();
        FileOutputStream fileOutputStream2 = new FileOutputStream(new File("D:\\test12.txt"), false);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream2);
        response.getWriter().println("list of student ---> <a href=\"\">daftar.jsp</a>");

And the serialized object will be read from “daftar.jsp” file,

<%@page import="com.edw.bean.Student"%>
<%@page import=""%>
<%@page import=""%>
<%@page import=""%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Daftar Nama</title>
        <h1>Registered Name is : </h1>
                FileInputStream fileInputStream = new FileInputStream(new File("D:\\test12.txt"));
                ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
                Student student = (Student)objectInputStream.readObject();
            }catch(Exception ex){                

Dont forget to register you servlet to web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Well it’s not too hard isnt it ;)


Enabling Remote Connection on PostgreSQL

Default Postgresql configuration only allow connection from localhost, if you want your PostgreSQL to accepting connection from other ip, there are some changes that you need to do.

First, you need to open file pg_hba.conf and edit “IPv4 local connections” part. Add other ip that you want to be connected to your database.

# IPv4 local connections:
host    all         all          trust
host 	all 		all 		  trust

After that, open file postgresql.conf and do some editing in “listen_addresses” part.

#listen_addresses = 'localhost'		# what IP address(es) to listen on;
listen_addresses = '*'
					# comma-separated list of addresses;
					# defaults to 'localhost', '*' = all
					# (change requires restart)

After restarting your postgresql , it can accept connection from other ip. ;-)


MyBatis Caching Using OSCache

In this example im trying to create a simple application using MyBatis cache ability. What is cache anyway? A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database and put it whether in memory or in file. Database access is necessary only when retrieving data that is not currently available in the cache. So basically not all queries are taken from database, but from cache instead.

As you can see here, MyBatis has lots of caching products. But on this example im using OSCache.
First, as always, a simple mysql table

        nama VARCHAR(10) NOT NULL,
        alamat VARCHAR(200),
        PRIMARY KEY (nama)
insert into contoh (nama, alamat) values ('edw', 'Jakarta');
insert into contoh (nama, alamat) values ('danu', 'Ciledug');
insert into contoh (nama, alamat) values ('kamplenk', 'Tangerang');
insert into contoh (nama, alamat) values ('tebek', 'BSD');
insert into contoh (nama, alamat) values ('nugie', 'Pamulang');
insert into contoh (nama, alamat) values ('samsu', 'Bandung');

And a simple java bean to represent my table,

package com.edw.bean;


public class Contoh implements Serializable {
    private String nama;
    private String alamat;

	// setter and getter

    public String toString(){
        return nama+" : "+alamat;

And a simple java interface to create query method

package com.edw.mapper;

import com.edw.bean.Contoh;
import java.util.List;

public interface ContohMapper {    
    List<Contoh> selectAll();

My xml query, please take a look at line 5.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-// Mapper 3.0//EN" "" >
<mapper namespace="com.edw.mapper.ContohMapper" >
	<cache type="org.mybatis.caches.oscache.OSCache"/>

    <resultMap id="ContohMap" type="com.edw.bean.Contoh" >
        <id column="nama" property="nama" jdbcType="VARCHAR" />
        <result column="alamat" property="alamat" jdbcType="VARCHAR" />
    <select id="selectAll" resultMap="ContohMap">
        SELECT * FROM contoh

And my xml configuration to load all my xml queries,

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-// Config 3.0//EN"
   <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost/test"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
        <mapper resource="com/edw/xml/ContohMapper.xml" />

A java class to load all my xml configurations,

package com.edw.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisSqlSessionFactory {

    protected static final SqlSessionFactory FACTORY;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/xml/Configuration.xml");
            FACTORY = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);

    public static SqlSessionFactory getSqlSessionFactory() {
        return FACTORY;

Now i create my main java class.

package com.edw.main;

import com.edw.bean.Contoh;
import com.edw.config.MyBatisSqlSessionFactory;
import com.edw.mapper.ContohMapper;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

public class Main {
    private Logger logger = Logger.getLogger(this.getClass());
    public Main(){       
    private void execute(){
        // test caching by doing select queries for 10 times
        for (int i = 0; i < 10; i++) {
            SqlSession session = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession();
            ContohMapper mapper = session.getMapper(ContohMapper.class);
            List<Contoh> contohs = mapper.selectAll();
            for (Contoh contoh : contohs) {
            try {
                logger.debug("sleeping for 3 seconds");
            } catch (Exception e) {

    public static void main(String[] args) {
        Main main = new Main();

Last, is create 2 properties file. One is for log4j configuration, and another one for oscache configuration.
This is my

# Global logging configuration

# Console output...
log4j.appender.stdout.layout.ConversionPattern=%d [%c{1}] %-5p %c:%L - %m%n

And this is my


If you run the application, you’ll notice that for the second queries it will take from cache instead of database. This is what written on my log console.

2012-05-20 02:06:11,687 [Connection] DEBUG java.sql.Connection:27 - ooo Connection Opened
2012-05-20 02:06:11,688 [AbstractConcurrentReadCache] DEBUG com.opensymphony.oscache.base.algorithm.AbstractConcurrentReadCache:694 - get called (key=1247278887:1786588787:com.edw.mapper.ContohMapper.selectAll:0:2147483647:SELECT * FROM contoh)
2012-05-20 02:06:11,688 [LoggingCache] DEBUG org.apache.ibatis.cache.decorators.LoggingCache:27 - Cache Hit Ratio [com.edw.mapper.ContohMapper]: 0.6666666666666666
2012-05-20 02:06:11,689 [Main] DEBUG com.edw.main.Main:31 - edw : Jakarta
2012-05-20 02:06:11,689 [Main] DEBUG com.edw.main.Main:31 - danu : Ciledug
2012-05-20 02:06:11,692 [Main] DEBUG com.edw.main.Main:31 - kamplenk : Tangerang
2012-05-20 02:06:11,692 [Main] DEBUG com.edw.main.Main:31 - tebek : BSD
2012-05-20 02:06:11,692 [Main] DEBUG com.edw.main.Main:31 - nugie : Pamulang
2012-05-20 02:06:11,693 [Main] DEBUG com.edw.main.Main:31 - samsu : Bandung
2012-05-20 02:06:11,693 [Connection] DEBUG java.sql.Connection:27 - xxx Connection Closed
2012-05-20 02:06:11,693 [Main] DEBUG com.edw.main.Main:36 - sleeping for 3 seconds
BUILD STOPPED (total time: 8 seconds)

This is my project structure on Netbeans7
mybatis oscache project structure