About Andreas Tjong

JAVA Programmer since 2008. Kettle designer as hobby since 2008.

Spring Web MVC – Simple CRUD with iBatis (Episode 5)


Persiapan:

  1. Sudah membaca artikel Spring Web MVC – Create Log File (Episode 3). Jika belum, silahkan baca artikel ini.
  2. Membaca doa sebelum memulai mengikuti artikel ini.

Note: Untuk postingan ini sudah mulai agak advance sedikit, saya coba menjelaskan secara perlahan, dan kalau anda bingung.

File-file yang dibutuhkan:

  1. jtds-1.2.4.jar —  silahkan download disini
  2. ibatis-sqlmap-2.3.4.726.jar — silahkan download disini
  3. c3p0-0.9.1.2.jar — silahkan download disini

Pada artikel ini saya akan coba memberikan contoh membuat sebuah aplikasi Simple CRUD dengan menggunakan iBatis. Untuk membuat sebuah aplikasi yang mengandung CRUD ada 2 pendekatan yang bisa biasanya saya gunakan. Yang pertama adalah membangun model Dao nya terlebih dahulu baru membangun view jsp nya, cara kedua adalah membangun flow pada view nya terlebih dahulu, setelah itu baru membangun model Dao nya. Pada contoh kali ini saya akan menggunakan cara yang kedua.

PART 1 – Membangun view

Anggap kita akan membuat data mahasiswa yang terdiri dari NIM, NAMA, dan UMUR (3 saja dulu ya, jangan terlalu banyak. :p). Lalu pada aplikasi ini kita akan membuat fasilitas untuk:

  1. Add New
  2. Edit
  3. Search
  4. Show All

Silahkan ikuti langkah2 berikut:

  1. pada package com.firstProgram.model buat class Mahasiswa.java
     package com.firstProgram.model;
    
    public class Mahasiswa {
     private String nim;
     private String nama;
     private Integer umur;
     public String getNim() {
     return nim;
     }
     public void setNim(String nim) {
     this.nim = nim;
     }
     public String getNama() {
     return nama;
     }
     public void setNama(String nama) {
     this.nama = nama;
     }
     public Integer getUmur() {
     return umur;
     }
     public void setUmur(Integer umur) {
     this.umur = umur;
     }
    }
    
    
  2. pada folder firstProgram/WebContent/WEB-INF/pages buat file mahasiswa_show.jsp
    <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 5</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <a href="<c:url value="/mahasiswa/all.asik" />">Show All</a>
     ---
     <a href="<c:url value="/mahasiswa/add.asik" />">Add New</a>
     ---
     <a href="<c:url value="/mahasiswa/search.asik" />">Search</a>
    
     <br />
     <br />
     <br />
     <table width="500" border="1" cellpadding="2" cellspacing="2">
     <tr>
     <th width="30%">NIM</th>
     <th width="50%">Nama</th>
     <th width="10%">Umur</th>
     <th width="20%" colspan="2">&nbsp;</th>
     </tr>
     <tr>
     <td>nim</td>
     <td>nama</td>
     <td>umur</td>
     <td>
     <form:form action="edit.asik">
     <input type="hidden" id="nim" name="nim" value="nim"/>
     <input type="hidden" id="nama" name="nama" value="nama"/>
     <input type="hidden" id="umur" name="umur" value="umur"/>
     <input type="submit" value="Edit" style="width:60px;"/>
     </form:form>
     </td>
     <td>
     <form:form action="delete.asik">
     <input type="hidden" id="nim" name="nim" value="nim"/>
     <input type="submit" value="Delete" style="width:60px;"/>
     </form:form>
     </td>
     </tr>
     </table>
     </body>
    </html>
    
  3. pada folder firstProgram/WebContent/WEB-INF/pages buat file mahasiswa_new.jsp
    <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 5</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <a href="<c:url value="/mahasiswa/all.asik" />">Show All</a>
     ---
     <a href="<c:url value="/mahasiswa/add.asik" />">Add New</a>
     ---
     <a href="<c:url value="/mahasiswa/search.asik" />">Search</a>
    
     <h1>Please Input:</h1>
     <form:form>
     <div>
     <label for="nim">NIM</label>
     <input type="text" id="nim" name="nim" value="nim"/>
     </div>
     <div>
     <label for="nama">Nama</label>
     <input type="text" id="nama" name="nama" value="nama"/>
     </div>
     <div>
     <label for="umur">Age</label>
     <input type="text" id="umur" name="umur" value="umur"/>
     </div>
     <div>
     <label>&nbsp;</label>
     <input type="submit" value="Save"/>
     <input type="reset" value="Cancel"/>
     </div>
     </form:form>
    
     <br />
     <br />
     <br />
     <table width="500" border="1" cellpadding="2" cellspacing="2">
     <tr>
     <th width="30%">NIM</th>
     <th width="50%">Nama</th>
     <th width="10%">Umur</th>
     <th width="20%" colspan="2">&nbsp;</th>
     </tr>
    
     <tr>
     <td>nim</td>
     <td>nama</td>
     <td>umur</td>
     <td>
     <form:form action="edit.asik">
     <input type="hidden" id="nim" name="nim" value="nim"/>
     <input type="hidden" id="nama" name="nama" value="nama"/>
     <input type="hidden" id="umur" name="umur" value="umur"/>
     <input type="submit" value="Edit" style="width:60px;"/>
     </form:form>
     </td>
     <td>
     <form:form action="delete.asik">
     <input type="hidden" id="nim" name="nim" value="nim"/>
     <input type="submit" value="Delete" style="width:60px;"/>
     </form:form>
     </td>
     </tr>
     </table>
     </body>
    </html>
    
  4. pada folder firstProgram/WebContent/WEB-INF/pages buat file mahasiswa_edit.jsp
    <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 5</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <a href="<c:url value="/mahasiswa/all.asik" />">Show All</a>
     ---
     <a href="<c:url value="/mahasiswa/add.asik" />">Add New</a>
     ---
     <a href="<c:url value="/mahasiswa/search.asik" />">Search</a>
    
     <h1>Please Input:</h1>
     <form:form>
     <div>
     <label for="nim">NIM</label>
     <input type="text" id="nim" name="nim" value="nim" READONLY="TRUE"/>
     </div>
     <div>
     <label for="nama">Nama</label>
     <input type="text" id="nama" name="nama" value="nama"/>
     </div>
     <div>
     <label for="umur">Umur</label>
     <input type="text" id="umur" name="umur" value="umur"/>
     </div>
     <div>
     <label>&nbsp;</label>
     <input type="submit" value="Update"/>
     <input type="reset" value="Cancel"/>
     </div>
     </form:form>
    
     <br />
     <br />
     <br />
     <table width="500" border="1" cellpadding="2" cellspacing="2">
     <tr>
     <th width="30%">NIM</th>
     <th width="50%">Nama</th>
     <th width="10%">Umur</th>
     <th width="20%" colspan="2">&nbsp;</th>
     </tr>
    
     <tr>
     <td>nim</td>
     <td>nama</td>
     <td>umur</td>
     <td>
     <form:form action="edit.asik">
     <input type="hidden" id="nim" name="nim" value="nim"/>
     <input type="hidden" id="nama" name="nama" value="nama"/>
     <input type="hidden" id="umur" name="umur" value="umur"/>
     <input type="submit" value="Edit" style="width:60px;"/>
     </form:form>
     </td>
     <td>
     <form:form action="delete.asik">
     <input type="hidden" id="nim" name="nim" value="nim"/>
     <input type="submit" value="Delete" style="width:60px;"/>
     </form:form>
     </td>
     </tr>
     </table>
     </body>
    </html>
    
  5. pada folder firstProgram/WebContent/WEB-INF/pages buat file mahasiswa_search.jsp
     <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 5</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <a href="<c:url value="/mahasiswa/all.asik" />">Show All</a>
     ---
     <a href="<c:url value="/mahasiswa/add.asik" />">Add New</a>
     ---
     <a href="<c:url value="/mahasiswa/search.asik" />">Search</a>
    
     <h1>Please Input:</h1>
     <form:form>
     <div>
     <label for="nim">NIM</label>
     <input type="text" id="nim" name="nim" value="${mahasiswa.nim}"/>
     </div>
     <div>
     <label>&nbsp;</label>
     <input type="submit" value="Search"/>
     <input type="reset" value="Cancel"/>
     </div>
     </form:form>
    
     <br />
     <br />
     <br />
    
     <table width="500" border="1" cellpadding="2" cellspacing="2">
     <tr>
     <th width="30%">NIM</th>
     <th width="50%">Nama</th>
     <th width="10%">Umur</th>
     <th width="20%" colspan="2">&nbsp;</th>
     </tr>
     <tr>
     <td>nim</td>
     <td>nama</td>
     <td>umur</td>
     <td>
     <form:form action="edit.asik">
     <input type="hidden" id="nim" name="nim" value="nim"/>
     <input type="hidden" id="nama" name="nama" value="nama"/>
     <input type="hidden" id="umur" name="umur" value="umur"/>
     <input type="submit" value="Edit" style="width:60px;"/>
     </form:form>
     </td>
     <td>
     <form:form action="delete.asik">
     <input type="hidden" id="nim" name="nim" value="nim"/>
     <input type="submit" value="Delete" style="width:60px;"/>
     </form:form>
     </td>
     </tr>
     </table>
    
     </body>
    </html>
    
  6. Pada package com.firstProgram.web buat Class MahasiswaAllController.java
     package com.firstProgram.web;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.firstProgram.dao.SimpleDao;
    
    @Controller
    public class MahasiswaAllController {
    
     private SimpleDao simpleDao;
     @Autowired
     public void setSimpleDao(SimpleDao simpleDao) {
     this.simpleDao = simpleDao;
     }
    
     @RequestMapping (value="/mahasiswa/all.asik", method=RequestMethod.GET)
     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     return new ModelAndView("mahasiswa/all", model);
     }
    
    }
    
    
  7. Pada package com.firstProgram.web buat Class MahasiswaAddController.java
    package com.firstProgram.web;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.firstProgram.dao.SimpleDao;
    import com.firstProgram.model.Mahasiswa;
    
    @Controller
    public class MahasiswaAddController {
    
     private SimpleDao simpleDao;
     @Autowired
     public void setSimpleDao(SimpleDao simpleDao) {
     this.simpleDao = simpleDao;
     }
    
     @RequestMapping (value="/mahasiswa/add.asik", method=RequestMethod.GET)
     public ModelAndView addNew(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     return new ModelAndView("mahasiswa/add", model);
     }
    
     @RequestMapping (value="/mahasiswa/add.asik", method=RequestMethod.POST)
     public ModelAndView saveNew(@RequestParam("nim")String nim
     ,@RequestParam("nama")String nama
     ,@RequestParam("umur")Integer umur
     ,HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     Mahasiswa mahasiswa = new Mahasiswa();
     mahasiswa.setNama(nama);
     mahasiswa.setNim(nim);
     mahasiswa.setUmur(umur);
    
     return new ModelAndView("mahasiswa/add", model);
     }
    }
    
    
  8. Pada package com.firstProgram.web buat Class MahasiswaEditController.java
     package com.firstProgram.web;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.firstProgram.dao.SimpleDao;
    import com.firstProgram.model.Mahasiswa;
    
    @Controller
    public class MahasiswaEditController {
    
     private SimpleDao simpleDao;
     @Autowired
     public void setSimpleDao(SimpleDao simpleDao) {
     this.simpleDao = simpleDao;
     }
    
     @RequestMapping (value="/mahasiswa/edit.asik", method=RequestMethod.POST)
     public ModelAndView saveNew(@RequestParam(value="nim", required=false)String nim
     ,@RequestParam(value="nama", required=false)String nama
     ,@RequestParam(value="umur", required=false)Integer umur
     ,HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     if(nama == null){
     nama = "";
     }
     if(umur == null){
     umur = 0;
     }
    
     Mahasiswa mahasiswa = new Mahasiswa();
     mahasiswa.setNama(nama);
     mahasiswa.setNim(nim);
     mahasiswa.setUmur(umur);
    
     return new ModelAndView("mahasiswa/edit", model);
     }
    }
    
    
  9. Pada package com.firstProgram.web buat Class MahasiswaSearchController.java
    package com.firstProgram.web;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.firstProgram.dao.SimpleDao;
    import com.firstProgram.model.Mahasiswa;
    
    @Controller
    public class MahasiswaSearchController {
    
     private SimpleDao simpleDao;
     @Autowired
     public void setSimpleDao(SimpleDao simpleDao) {
     this.simpleDao = simpleDao;
     }
    
     @RequestMapping (value="/mahasiswa/search.asik", method=RequestMethod.GET)
     public ModelAndView search(HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     return new ModelAndView("mahasiswa/search", model);
     }
    
     @RequestMapping (value="/mahasiswa/search.asik", method=RequestMethod.POST)
     public ModelAndView saveNew(@RequestParam(value="nim", required=false)String nim
     ,HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     return new ModelAndView("mahasiswa/search", model);
     }
    }
    
    
  10. Edit file index.jsp
     <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <%-- Redirected because we can't set the welcome page to a virtual URL. --%>
    <c:redirect url="/mahasiswa/all.asik"/>
    
  11. Edit file view.properties
    pages/hello.url = /WEB-INF/pages/hello.jsp
    pages/hello.class= org.springframework.web.servlet.view.JstlView
    
    pages/excell.url = /WEB-INF/pages/excell.jsp
    pages/excell.class= org.springframework.web.servlet.view.JstlView
    
    pages/excellReport.class = com.firstProgram.report.FirstProgramExcell
    
    mahasiswa/all.url = /WEB-INF/pages/mahasiswa_show.jsp
    mahasiswa/all.class = org.springframework.web.servlet.view.JstlView
    
    mahasiswa/add.url = /WEB-INF/pages/mahasiswa_new.jsp
    mahasiswa/add.class = org.springframework.web.servlet.view.JstlView
    
    mahasiswa/edit.url = /WEB-INF/pages/mahasiswa_edit.jsp
    mahasiswa/edit.class = org.springframework.web.servlet.view.JstlView
    
    mahasiswa/search.url = /WEB-INF/pages/mahasiswa_search.jsp
    mahasiswa/search.class = org.springframework.web.servlet.view.JstlView
    
    
  12. Coba jalankan aplikasi anda. http://localhost:8080/firstProgram . Pastikan flow data dari tiap jsp nya sudah benar (jika submit makan masuk ke dalam parameter yang dimaksud.

PART 2 – Membangun model Dao

Database yang saya gunakan adalah MS SQL Server 2000. Coba anda perhatikan 3 library yang dibutuhkan diatas:

  1. jtds-1.2.4.jar – ini adalah driver yang dibutuhkan untuk koneksi ke database MS SQL Server
  2. ibatis-sqlmap-2.3.4.726.jar – ini adalah library iBatis yang akan digunakan untuk mapping database ke class java.
  3. c3p0-0.9.1.2.jar – ini adalah library yang digunakan untuk connection pooling. Dengan menggunakan connection pooling artinya kita tidak perlu create connection ke database setiap kali transaksi. Pada aplikasi Web, umumnya koneksi ke database hanya di create pada saat server Start Up saja.

Anggap database yang saya gunakan:

  • Server:     localhost
  • Database:   testing

Pertama create table pada database:


CREATE TABLE [dbo].[MAHASISWA_2011] (

[NIM] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,

[NAMA] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[UMUR] [int] NULL
 ) ON [PRIMARY]

Silahkan ikuti langkah2 berikut:

  1. Download library-library yang saya sebutkan pada awal artikel lalu diinclude ke dalam project firstProgram
  2. Edit web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
     <display-name>firstProgram</display-name>
    
     <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/applicationContext*.xml</param-value>
     </context-param>
     <listener>
     <listener-class>
     org.springframework.web.context.ContextLoaderListener
     </listener-class>
     </listener>
    
     <filter>
     <filter-name>LoggerContextFilter</filter-name>
     <filter-class>ch.qos.logback.classic.selector.servlet.LoggerContextFilter</filter-class>
     </filter>
     <filter-mapping>
     <filter-name>LoggerContextFilter</filter-name>
     <url-pattern>/*</url-pattern>
     </filter-mapping>
    
     <servlet>
     <servlet-name>tjong</servlet-name>
     <servlet-class>
     org.springframework.web.servlet.DispatcherServlet
     </servlet-class>
     <load-on-startup>1</load-on-startup>
     </servlet>
     <servlet-mapping>
     <servlet-name>tjong</servlet-name>
     <url-pattern>*.asik</url-pattern>
     </servlet-mapping>
     <servlet-mapping>
     <servlet-name>tjong</servlet-name>
     <url-pattern>*.xls</url-pattern>
     </servlet-mapping>
    
     <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>
    </web-app>
    
  3. Pada folder firstProgram/WebContent/WEB-INF create file applicationContext-ibatis.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:jee="http://www.springframework.org/schema/jee"
     xmlns:tx="http://www.springframework.org/schema/tx"
     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
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="exampleDataSource"/>
     </bean>
    
     <context:property-placeholder location="classpath:jdbc.properties"/>
    
     <bean id="sqlMapClient"  class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
     <property name="configLocation" value="classpath:sql-map-config.xml"/>
     </bean>
    
     <bean id="exampleDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">
     <property name="driverClass" value="${jdbc.driverClassName}"/>
     <property name="jdbcUrl" value="${jdbc.url}"/>
     <property name="user" value="${jdbc.username}"/>
     <property name="password" value="${jdbc.password}"/>
     </bean>
    
     <bean id="simpleDao" class="com.firstProgram.dao.SimpleDaoImpl">
     <property name="dataSource" ref="exampleDataSource"/>
     <property name="sqlMapClient" ref="sqlMapClient"/>
     </bean>
    
    </beans>
    
  4. Pada folder firstProgram/resources, create file sql-map-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
     "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
    
    <sqlMapConfig>
     <sqlMap resource="sqlmaps/simple.xml" />
    </sqlMapConfig>
    
  5. Pada folder firstProgram/resources, create file jdbc.properties
    jdbc.driverClassName=net.sourceforge.jtds.jdbc.Driver
    jdbc.url=jdbc:jtds:sqlserver://localhost/testing
    jdbc.username=admin
    jdbc.password=andreas
    
  6. Pada folder firstProgram/resources, create folder sqlmaps
  7. Pada folder firstProgram/resources/sqlmaps, create file simple.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    
    <!DOCTYPE sqlMap
     PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
     "http://ibatis.apache.org/dtd/sql-map-2.dtd">
    
    <sqlMap namespace="simple">
    
     <typeAlias alias="Mahasiswa" type="com.firstProgram.model.Mahasiswa"/>
     <resultMap id="Mahasiswa">
     <result property="nim" column="nim"/>
     <result property="nama" column="nama"/>
     <result property="umur" column="umur"/>
     </resultMap>
    
     <select id="getAllMahasiswa" resultMap="Mahasiswa">
     SELECT nim, nama, umur
     FROM MAHASISWA_2011
     ORDER BY nim
     </select>
    
     <select id="getMahasiswa" resultMap="Mahasiswa" parameterClass="java.util.HashMap">
     SELECT nim, nama, umur
     FROM MAHASISWA_2011
     WHERE NIM = #nim#
     ORDER BY nim
     </select>
    
     <delete id="deleteMahasiswa" parameterClass="java.util.HashMap">
     DELETE FROM MAHASISWA_2011
     WHERE NIM = #nim#
     </delete>
    
     <update id="updateMahasiswa" parameterClass="java.util.HashMap">
     UPDATE MAHASISWA_2011
     SET NIM = #nim#
     , NAMA = #nama#
     , UMUR = #umur#
     WHERE NIM = #nim#
     </update>
    
     <insert id="addMahasiswa" parameterClass="java.util.HashMap">
     INSERT into MAHASISWA_2011(NIM, NAMA, UMUR)
     VALUES(#nim#,#nama#,#umur#)
     </insert>
    
    </sqlMap>
    
  8. Create package com.firstProgram.dao
  9. Pada package com.firstProgram.dao, create file SimpleDao.java
    package com.firstProgram.dao;
    
    import java.util.List;
    
    import com.firstProgram.model.Mahasiswa;
    
    public interface SimpleDao {
     public Mahasiswa getMahasiswa(String nim);
     public List<Mahasiswa> getAllMahasiswa();
    
     public void insertMahasiswa(Mahasiswa mahasiswa);
     public void updateMahasiswa(Mahasiswa mahasiswa);
     public void deleteMahasiswa(Mahasiswa mahasiswa);
    }
    
    
  10. Pada package com.firstProgram.dao, create file SimpleDaoImpl.java
    package com.firstProgram.dao;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
    
    import com.firstProgram.model.Mahasiswa;
    
    public class SimpleDaoImpl extends SqlMapClientDaoSupport implements SimpleDao {
    
     public void deleteMahasiswa(Mahasiswa mahasiswa) {
     Map input = new HashMap();
     input.put("nim", mahasiswa.getNim());
    
     getSqlMapClientTemplate().delete("deleteMahasiswa", input);
     }
    
     public List<Mahasiswa> getAllMahasiswa() {
     return (List<Mahasiswa>) getSqlMapClientTemplate().queryForList("getAllMahasiswa");
     }
    
     public Mahasiswa getMahasiswa(String nim) {
     Map input = new HashMap();
     input.put("nim", nim);
    
     return (Mahasiswa) getSqlMapClientTemplate().queryForObject("getMahasiswa", input);
     }
    
     public void updateMahasiswa(Mahasiswa mahasiswa) {
     Map input = new HashMap();
     input.put("nim", mahasiswa.getNim());
     input.put("nama", mahasiswa.getNama());
     input.put("umur", mahasiswa.getUmur());
    
     getSqlMapClientTemplate().update("updateMahasiswa", input);
     }
    
     public void insertMahasiswa(Mahasiswa mahasiswa) {
     Map input = new HashMap();
     input.put("nim", mahasiswa.getNim());
     input.put("nama", mahasiswa.getNama());
     input.put("umur", mahasiswa.getUmur());
    
     getSqlMapClientTemplate().insert("addMahasiswa", input);
     }
    }
    
    
  11. Pada package com.firstProgram.web, edit file MahasiswaAddController.java
    package com.firstProgram.web;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.firstProgram.dao.SimpleDao;
    import com.firstProgram.model.Mahasiswa;
    
    @Controller
    public class MahasiswaAddController {
    
     private SimpleDao simpleDao;
     @Autowired
     public void setSimpleDao(SimpleDao simpleDao) {
     this.simpleDao = simpleDao;
     }
    
     @RequestMapping (value="/mahasiswa/add.asik", method=RequestMethod.GET)
     public ModelAndView addNew(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     return new ModelAndView("mahasiswa/add", model);
     }
    
     @RequestMapping (value="/mahasiswa/add.asik", method=RequestMethod.POST)
     public ModelAndView saveNew(@RequestParam("nim")String nim
     ,@RequestParam("nama")String nama
     ,@RequestParam("umur")Integer umur
     ,HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     Mahasiswa mahasiswa = new Mahasiswa();
     mahasiswa.setNama(nama);
     mahasiswa.setNim(nim);
     mahasiswa.setUmur(umur);
    
     simpleDao.insertMahasiswa(mahasiswa);
    
     return new ModelAndView("mahasiswa/add", model);
     }
    }
    
    
  12. Pada package com.firstProgram.web, edit file MahasiswaAllController.java
    package com.firstProgram.web;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.firstProgram.dao.SimpleDao;
    
    @Controller
    public class MahasiswaAllController {
    
     private SimpleDao simpleDao;
     @Autowired
     public void setSimpleDao(SimpleDao simpleDao) {
     this.simpleDao = simpleDao;
     }
    
     @RequestMapping (value="/mahasiswa/all.asik", method=RequestMethod.GET)
     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
     model.put("mahasiswas", simpleDao.getAllMahasiswa());
    
     return new ModelAndView("mahasiswa/all", model);
     }
    
    }
    
    
  13. Pada package com.firstProgram.web, edit file MahasiswaEditController.java
    package com.firstProgram.web;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.firstProgram.dao.SimpleDao;
    import com.firstProgram.model.Mahasiswa;
    
    @Controller
    public class MahasiswaEditController {
    
     private SimpleDao simpleDao;
     @Autowired
     public void setSimpleDao(SimpleDao simpleDao) {
     this.simpleDao = simpleDao;
     }
    
     @RequestMapping (value="/mahasiswa/edit.asik", method=RequestMethod.POST)
     public ModelAndView saveNew(@RequestParam(value="nim", required=false)String nim
     ,@RequestParam(value="nama", required=false)String nama
     ,@RequestParam(value="umur", required=false)Integer umur
     ,HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     if(nama == null){
     nama = "";
     }
     if(umur == null){
     umur = 0;
     }
    
     Mahasiswa mahasiswa = new Mahasiswa();
     mahasiswa.setNama(nama);
     mahasiswa.setNim(nim);
     mahasiswa.setUmur(umur);
    
     simpleDao.updateMahasiswa(mahasiswa);
     mahasiswa = simpleDao.getMahasiswa(nim);
     model.put("mahasiswa", mahasiswa);
    
     model.put("mahasiswas", simpleDao.getAllMahasiswa());
    
     return new ModelAndView("mahasiswa/edit", model);
     }
    }
    
    
  14. Pada package com.firstProgram.web, edit file MahasiswaSearchController.java
    package com.firstProgram.web;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.firstProgram.dao.SimpleDao;
    import com.firstProgram.model.Mahasiswa;
    
    @Controller
    public class MahasiswaSearchController {
    
     private SimpleDao simpleDao;
     @Autowired
     public void setSimpleDao(SimpleDao simpleDao) {
     this.simpleDao = simpleDao;
     }
    
     @RequestMapping (value="/mahasiswa/search.asik", method=RequestMethod.GET)
     public ModelAndView search(HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     return new ModelAndView("mahasiswa/search", model);
     }
    
     @RequestMapping (value="/mahasiswa/search.asik", method=RequestMethod.POST)
     public ModelAndView saveNew(@RequestParam(value="nim", required=false)String nim
     ,HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     Map model = new HashMap();
    
     Mahasiswa mahasiswa = new Mahasiswa();
     mahasiswa = simpleDao.getMahasiswa(nim);
     model.put("mahasiswa", mahasiswa);
    
     return new ModelAndView("mahasiswa/search", model);
     }
    }
    
    
  15. Edit file mahasiswa_edit.jsp
    <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 5</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <a href="<c:url value="/mahasiswa/all.asik" />">Show All</a>
     ---
     <a href="<c:url value="/mahasiswa/add.asik" />">Add New</a>
     ---
     <a href="<c:url value="/mahasiswa/search.asik" />">Search</a>
    
     <h1>Please Input:</h1>
     <form:form>
     <div>
     <label for="nim">NIM</label>
     <input type="text" id="nim" name="nim" value="${mahasiswa.nim}" READONLY="TRUE"/>
     </div>
     <div>
     <label for="nama">Nama</label>
     <input type="text" id="nama" name="nama" value="${mahasiswa.nama}"/>
     </div>
     <div>
     <label for="umur">Umur</label>
     <input type="text" id="umur" name="umur" value="${mahasiswa.umur}"/>
     </div>
     <div>
     <label>&nbsp;</label>
     <input type="submit" value="Update"/>
     <input type="reset" value="Cancel"/>
     </div>
     </form:form>
    
     <br />
     <br />
     <br />
     <table width="500" border="1" cellpadding="2" cellspacing="2">
     <tr>
     <th width="30%">NIM</th>
     <th width="50%">Nama</th>
     <th width="10%">Umur</th>
     <th width="20%" colspan="2">&nbsp;</th>
     </tr>
    
     <c:forEach items="${mahasiswas}" var="mahasiswa" varStatus="status">
     <c:if test="${status.index % 2 == 0}">
     <tr>
     </c:if>
     <c:if test="${status.index % 2 == 1}">
     <tr>
     </c:if>
     <td>${mahasiswa.nim}</td>
     <td>${mahasiswa.nama}</td>
     <td>${mahasiswa.umur}</td>
     <td>
     <form:form action="edit.asik">
     <input type="hidden" id="nim" name="nim" value="${mahasiswa.nim}"/>
     <input type="hidden" id="nama" name="nama" value="${mahasiswa.nama}"/>
     <input type="hidden" id="umur" name="umur" value="${mahasiswa.umur}"/>
     <input type="submit" value="Edit" style="width:60px;"/>
     </form:form>
     </td>
     <td>
     <form:form action="delete.asik">
     <input type="hidden" id="nim" name="nim" value="${mahasiswa.nim}"/>
     <input type="submit" value="Delete" style="width:60px;"/>
     </form:form>
     </td>
     </tr>
     </c:forEach>
     </table>
     </body>
    </html>
    
  16. Edit file mahasiswa_new.jsp
    <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 5</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <a href="<c:url value="/mahasiswa/all.asik" />">Show All</a>
     ---
     <a href="<c:url value="/mahasiswa/add.asik" />">Add New</a>
     ---
     <a href="<c:url value="/mahasiswa/search.asik" />">Search</a>
    
     <h1>Please Input:</h1>
     <form:form>
     <div>
     <label for="nim">NIM</label>
     <input type="text" id="nim" name="nim" value="${mahasiswa.nim}"/>
     </div>
     <div>
     <label for="nama">Nama</label>
     <input type="text" id="nama" name="nama" value="${mahasiswa.nama}"/>
     </div>
     <div>
     <label for="umur">Age</label>
     <input type="text" id="umur" name="umur" value="${mahasiswa.umur}"/>
     </div>
     <div>
     <label>&nbsp;</label>
     <input type="submit" value="Save"/>
     <input type="reset" value="Cancel"/>
     </div>
     </form:form>
    
     <br />
     <br />
     <br />
     <table width="500" border="1" cellpadding="2" cellspacing="2">
     <tr>
     <th width="30%">NIM</th>
     <th width="50%">Nama</th>
     <th width="10%">Umur</th>
     <th width="20%" colspan="2">&nbsp;</th>
     </tr>
    
     <c:forEach items="${mahasiswas}" var="mahasiswa" varStatus="status">
     <c:if test="${status.index % 2 == 0}">
     <tr>
     </c:if>
     <c:if test="${status.index % 2 == 1}">
     <tr>
     </c:if>
     <td>${mahasiswa.nim}</td>
     <td>${mahasiswa.nama}</td>
     <td>${mahasiswa.umur}</td>
     <td>
     <form:form action="edit.asik">
     <input type="hidden" id="nim" name="nim" value="${mahasiswa.nim}"/>
     <input type="hidden" id="nama" name="nama" value="${mahasiswa.nama}"/>
     <input type="hidden" id="umur" name="umur" value="${mahasiswa.umur}"/>
     <input type="submit" value="Edit" style="width:60px;"/>
     </form:form>
     </td>
     <td>
     <form:form action="delete.asik">
     <input type="hidden" id="nim" name="nim" value="${mahasiswa.nim}"/>
     <input type="submit" value="Delete" style="width:60px;"/>
     </form:form>
     </td>
     </tr>
     </c:forEach>
     </table>
     </body>
    </html>
    
  17. Edit file mahasiswa_search.jsp
    <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 5</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <a href="<c:url value="/mahasiswa/all.asik" />">Show All</a>
     ---
     <a href="<c:url value="/mahasiswa/add.asik" />">Add New</a>
     ---
     <a href="<c:url value="/mahasiswa/search.asik" />">Search</a>
    
     <h1>Please Input:</h1>
     <form:form>
     <div>
     <label for="nim">NIM</label>
     <input type="text" id="nim" name="nim" value="${mahasiswa.nim}"/>
     </div>
     <div>
     <label>&nbsp;</label>
     <input type="submit" value="Search"/>
     <input type="reset" value="Cancel"/>
     </div>
     </form:form>
    
     <br />
     <br />
     <br />
    
     <c:if test = "${!(empty mahasiswa)}">
     <table width="500" border="1" cellpadding="2" cellspacing="2">
     <tr>
     <th width="30%">NIM</th>
     <th width="50%">Nama</th>
     <th width="10%">Umur</th>
     <th width="20%" colspan="2">&nbsp;</th>
     </tr>
     <tr>
     <td>${mahasiswa.nim}</td>
     <td>${mahasiswa.nama}</td>
     <td>${mahasiswa.umur}</td>
     <td>
     <form:form action="edit.asik">
     <input type="hidden" id="nim" name="nim" value="${mahasiswa.nim}"/>
     <input type="hidden" id="nama" name="nama" value="${mahasiswa.nama}"/>
     <input type="hidden" id="umur" name="umur" value="${mahasiswa.umur}"/>
     <input type="submit" value="Edit" style="width:60px;"/>
     </form:form>
     </td>
     <td>
     <form:form action="delete.asik">
     <input type="hidden" id="nim" name="nim" value="${mahasiswa.nim}"/>
     <input type="submit" value="Delete" style="width:60px;"/>
     </form:form>
     </td>
     </tr>
     </table>
     </c:if>
     </body>
    </html>
    
  18. Edit file mahasiswa_show.jsp
    <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 5</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <a href="<c:url value="/mahasiswa/all.asik" />">Show All</a>
     ---
     <a href="<c:url value="/mahasiswa/add.asik" />">Add New</a>
     ---
     <a href="<c:url value="/mahasiswa/search.asik" />">Search</a>
    
     <br />
     <br />
     <br />
     <table width="500" border="1" cellpadding="2" cellspacing="2">
     <tr>
     <th width="30%">NIM</th>
     <th width="50%">Nama</th>
     <th width="10%">Umur</th>
     <th width="20%" colspan="2">&nbsp;</th>
     </tr>
    
     <c:forEach items="${mahasiswas}" var="mahasiswa" varStatus="status">
     <c:if test="${status.index % 2 == 0}">
     <tr>
     </c:if>
     <c:if test="${status.index % 2 == 1}">
     <tr>
     </c:if>
     <td>${mahasiswa.nim}</td>
     <td>${mahasiswa.nama}</td>
     <td>${mahasiswa.umur}</td>
     <td>
     <form:form action="edit.asik">
     <input type="hidden" id="nim" name="nim" value="${mahasiswa.nim}"/>
     <input type="hidden" id="nama" name="nama" value="${mahasiswa.nama}"/>
     <input type="hidden" id="umur" name="umur" value="${mahasiswa.umur}"/>
     <input type="submit" value="Edit" style="width:60px;"/>
     </form:form>
     </td>
     <td>
     <form:form action="delete.asik">
     <input type="hidden" id="nim" name="nim" value="${mahasiswa.nim}"/>
     <input type="submit" value="Delete" style="width:60px;"/>
     </form:form>
     </td>
     </tr>
     </c:forEach>
     </table>
     </body>
    </html>
    
  19. Silahkan testing aplikasi anda, http://localhost:8080/firstProgram

Kira-kira result nya seperti ini:

Spring Web MVC – Create Excel File (Episode 4)


Persiapan:

  1. Sudah membaca artikel Spring Web MVC – Create Log File (Episode 3). Jika belum, silahkan baca artikel ini

File-file yang dibutuhkan:

  1. jxl-2.6.3.jar — silahkan download disini.

Pada artikel ini saya kan memberikan contoh sederhana – bagaimana cara membuat file excel melalui Spring MVC. Silahkan ikuti langkah2 berikut:

  1. Download library di atas, lalu diinclude ke dalam project firstProgram
  2. Buat file FirstProgramExcell.java pada package com.firstProgram.report.java :
     package com.firstProgram.report;
    
    import jxl.write.*;
    import jxl.format.Alignment;
    
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.servlet.view.document.AbstractJExcelView;
    
    public class FirstProgramExcell extends AbstractJExcelView {
    
     private static final Logger logger = LoggerFactory.getLogger(FirstProgramExcell.class);
    
     protected void buildExcelDocument(Map model,
     WritableWorkbook workbook,
     HttpServletRequest request,
     HttpServletResponse response) throws Exception {
    
     WritableFont normal = new WritableFont(WritableFont.ARIAL, 9);
     WritableFont bolder = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
    
     WritableCellFormat bolderCenterFormat = new WritableCellFormat(bolder);
     bolderCenterFormat.setAlignment(Alignment.CENTRE);
     bolderCenterFormat.setBorder(Border.ALL, BorderLineStyle.MEDIUM);
    
     WritableCellFormat normalLeftFormat = new WritableCellFormat(normal);
     normalLeftFormat.setAlignment(Alignment.LEFT);
     normalLeftFormat.setBorder(Border.ALL, BorderLineStyle.MEDIUM);
    
     WritableSheet sheet;
    
     sheet = workbook.createSheet("Example", 1);
    
     sheet.setColumnView(0, 20);
     sheet.setColumnView(1, 30);
    
     /*Ini bagian datanya*/
     String firstName = (String) model.get("firstName");
     String lastName = (String) model.get("lastName");
     String speciality = (String) model.get("speciality");
    
     int row = 0;
     int column = 0;
     sheet.addCell(new Label(column, row, "First Name", bolderCenterFormat ));
     sheet.addCell(new Label(column+1, row, firstName, normalLeftFormat ));
    
     row = row + 1;
     sheet.addCell(new Label(column, row, "Last Name", bolderCenterFormat ));
     sheet.addCell(new Label(column+1, row, lastName, normalLeftFormat ));
    
     row = row + 1;
     sheet.addCell(new Label(column, row, "Speciality", bolderCenterFormat ));
     sheet.addCell(new Label(column+1, row, speciality, normalLeftFormat ));
    
     }
    }
    
    
  3. Edit file ExcellExampleController.java di package com.firstProgram.web
     package com.firstProgram.web;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    @Controller
    public class ExcellExampleController{
    
     private static final Logger logger = LoggerFactory.getLogger(ExcellExampleController.class);
    
     @RequestMapping (value="/excell.asik", method=RequestMethod.GET)
     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
     return new ModelAndView("pages/excell");
     }
    
     @RequestMapping (value="/excell.xls", method=RequestMethod.POST)
     public ModelAndView generateExcell( @RequestParam(value="firstName",required=false) String firstName
     ,@RequestParam(value="lastName",required=false) String lastName
     ,@RequestParam(value="speciality",required=false) String speciality
     ,HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     logger.info("First Name : '{}'", firstName);
     logger.info("Last Name : '{}'", lastName);
     logger.info("Speciality : '{}'", speciality);
    
     Map model = new HashMap();
     model.put("firstName", firstName);
     model.put("lastName", lastName);
     model.put("speciality", speciality);
    
     return new ModelAndView("pages/excellReport", model);
     }
    
    }
    
    
  4. Edit view.properties
     pages/hello.url = /WEB-INF/pages/hello.jsp
    pages/hello.class= org.springframework.web.servlet.view.JstlView
    
    pages/excell.url = /WEB-INF/pages/excell.jsp
    pages/excell.class= org.springframework.web.servlet.view.JstlView
    
    pages/excellReport.class = com.firstProgram.report.FirstProgramExcell
    
  5. Edit excell.jsp
    <!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.1 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
     <head>
     <title>Episode 3</title>
     <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
     </head>
     <body>
     <h1>Please Input:</h1>
     <form:form action="excell.xls" target="_blank">
     <div>
     <label for="firstName">First Name</label>
     <input type="text" id="firstName" name="firstName" value="${firstName}"/>
     </div>
     <div>
     <label for="lastName">Last Name</label>
     <input type="text" id="lastName" name="lastName" value="${lastName}"/>
     </div>
     <div>
     <label for="speciality">Speciality</label>
     <input type="text" id="speciality" name="speciality" value="${speciality}"/>
     </div>
     <div>
     <label>&nbsp;</label>
     <input type="submit" value="Next"/>
     <input type="reset" value="Cancel"/>
     </div>
     </form:form>
     </body>
    </html>
    
  6. Testing aplikasi anda. http://localhost:8080/firstProgram/excell.asik
  7. Coba masukkan inputan lalu di submit. Jika muncul page save download link seperti dibawah, berarti anda sudah sukses menjalankan nya, jika tidak berarti ada yang salah.

Spring Web MVC – Create Log File (Episode 3)


Persiapan:

  1. Tau cara Start New (Dynamic Web) Project menggunakan Eclipse. Jika belum tahu silahkan baca artikel ini
  2. Sudah membaca artikel Spring Web MVC – Quick Start with Eclipse (Episode 1). Jika belum, silahkan baca artikel ini
  3. Sudah membaca artikel Spring Web MVC – Quick Start with Eclipse (Episode 2). Jika belum, silahkan baca artikel ini

File-file yang dibutuhkan:

  1. slf4j-api-1.6.1.jar – silahkan download disini
  2. standard-1.1.2.jar – silahkan download disini
  3. logback-core-0.9.27.jar- silahkan download disini
  4. logback-classic-0.9.27.jar- silahkan download disini
  5. logback-access-0.9.27.jar- silahkan download disini

Salah satu hal yang penting dalam mebuat sebuah aplikasi adalah adanya log, gunanya adalah mentrace jalannya aplikasi – siapa tahu ada error. Untuk contoh ini kita akan menggunakan library sl4j java. File-file pendukung nya dapat anda lihat pada list di atas.

Silahkan ikuti langkah2 berikut:

  1. Tambahkan file2 diatas ke dalam library anda.
  2. Edit web.xml. Tambah beberapa baris code, sehingga menjadi sperti ini:
     <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4"
    	xmlns="http://java.sun.com/xml/ns/j2ee"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
    	<display-name>firstProgram</display-name>
    
    	<filter>
    	  	<filter-name>LoggerContextFilter</filter-name>
    	  	<filter-class>ch.qos.logback.classic.selector.servlet.LoggerContextFilter</filter-class>
    	</filter>
    	<filter-mapping>
    		<filter-name>LoggerContextFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    
        <servlet>
            <servlet-name>tjong</servlet-name>
            <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>tjong</servlet-name>
            <url-pattern>*.asik</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>tjong</servlet-name>
            <url-pattern>*.xls</url-pattern>
        </servlet-mapping>
    
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    
    

    Edited 23 Maret 2011 09:03 AM: thanks to gery.

  3. Buat file logback.xml di folder resources.
    <?xml version="1.0" encoding="UTF-8"?>
    
    <configuration>
    	<appender name="FILE"
    		class="ch.qos.logback.core.rolling.RollingFileAppender">
    		<file>firstProgram.log</file>\
    		<rollingPolicy
    			class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    			<FileNamePattern>
    				firstProgram.%d{yyyy-MM-dd}.log
    			</FileNamePattern>
    		</rollingPolicy>
    		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
    			<pattern>
    				%date{ISO8601} %level [%thread] %logger{10} [%file : %line]	%msg%n
    			</pattern>
    		</encoder>
    	</appender>
    
    	<appender name="STDOUT"
    		class="ch.qos.logback.core.ConsoleAppender">
    		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
    			<pattern>
    				%date{ISO8601} %level %msg%n
    			</pattern>
    		</encoder>
    	</appender>
    
    	<root>
    		<level value="debug" />
    		<appender-ref ref="STDOUT" />
            <appender-ref ref="FILE" />
        </root>
    </configuration>
    
    

    Edited 23 Maret 2011 09:03 AM: thanks to gery.

  4. Buat Class ExcellExampleController.java pada package com.firstProgram.web
    package com.firstProgram.web;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import java.io.IOException;
    
    @Controller
    public class ExcellExampleController{
    
     private static final Logger logger = LoggerFactory.getLogger(ExcellExampleController.class);
    
     @RequestMapping (value="/excell.asik", method=RequestMethod.GET)
     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
     return new ModelAndView("pages/excell");
     }
    
     @RequestMapping (value="/excell.xls", method=RequestMethod.POST)
     public ModelAndView generateExcell( @RequestParam(value="firstName",required=false) String firstName
     ,@RequestParam(value="lastName",required=false) String lastName
     ,@RequestParam(value="speciality",required=false) String speciality
     ,HttpServletRequest request
     ,HttpServletResponse response)
     throws ServletException, IOException {
    
     logger.info("First Name : '{}'", firstName);
     logger.info("Last Name : '{}'", lastName);
     logger.info("Speciality : '{}'", speciality);
    
     return new ModelAndView("pages/excell");
     }
    
    }
    
    
  5. Edit file view.properties:
    pages/hello.url = /WEB-INF/pages/hello.jsp
    pages/hello.class= org.springframework.web.servlet.view.JstlView
    
    pages/excell.url = /WEB-INF/pages/excell.jsp
    pages/excell.class= org.springframework.web.servlet.view.JstlView
    
  6. Buat file excell.jsp pada folder firstProgram/WebContent/WEB-INF/pages
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
    <title>Episode 3</title>
    <link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <h1>Please Input:</h1>
    <div><label for="firstName">First Name</label>
    <input id="firstName" name="firstName" type="text" value="${firstName}" /></div>
    <div><label for="lastName">Last Name</label>
    <input id="lastName" name="lastName" type="text" value="${lastName}" /></div>
    <div><label for="speciality">Speciality</label>
    <input id="speciality" name="speciality" type="text" value="${speciality}" /></div>
    <div><label> </label>
    <input type="submit" value="Next" />
    <input type="reset" value="Cancel" /></div>
    </body>
    </html>
    
  7. Buat folder css pada folder firstProgram/WebContent
  8. Buat file style.css di folder firstProgram/WebContent/css
    * { font: 11px verdana, Verdana,DIN-Light sans-serif; }
    
    body {
    margin:0;
    padding:0;
    background:#f9f9f9;
    }
    
    h1{
     font: 30px verdana;
    }
    
    form label {
     width:120px;
     display: inline-block;
    }
    
    form input {
     width:180px;
     margin-top:10px;
     vertical-align: medium;
    }
    
  9. Testing aplikasi anda. http://localhost:8080/firstProgram/excell.asik
  10. Coba masukkan inputan lalu di submit. Kemudian check console anda.

Spring Web MVC – Quick Start with Eclipse (Episode 2)


Persiapan:

  1. Tau cara Start New (Dynamic Web) Project menggunakan Eclipse. Jika belum tahu silahkan baca artikel ini
  2. Sudah membaca artikel Spring Web MVC – Quick Start with Eclipse (Episode 1). Jika belum, silahkan baca artikel ini

Apakah anda sudah mengerti alur dari program yang sudah anda buat pada Episode 1? Jika belum, akan saya coba jelaskan agak detail:

  1. Anda (client) merequest alamat http://localhost:8080/firstProgram/hello.asik
  2. Web Server akan membaca settingan web.xml, disitu kita deklarasikan kalau ada request yang berakhiran dengan .asik maka akan diproses oleh Class org.springframework.web.servlet.DispatcherServlet, dengan settingan yang dibuat ada di tjong-servlet.xml
  3. Lalu si Web Server akan membaca settingan lagi di tjong-servlet.xml, disitu kita deklarasikan, jika ada yang merequest page “/hello.asik” akan diatur oleh Controller class=”com.firstProgram.web.HelloController
  4. Web Server akan membaca class com.firstProgram.web.HelloController, pada class HelloController, kita sudah mendeklarasikan untuk menampilkan file pages/hello.jsp. Maka Web Server akan menampilkan pages/hello.jsp kepada Anda (client).

Coba anda perhatikan, jika anda ingin membuat banyak page, pasti akan sangat merepotkan jika harus mendeklarasikan satu persatu file yang anda buat ke dalam tjong-servlet.xml (Khusus untuk controler, anda harus mendeklarasikan satu persatu Controller untuk page yang anda buat). Untuk mengatasi hal tersebut – Spring telah mempersiapkan beberapa optional untuk mengatur konfigurasi Controller dan View – silahkan baca (http://static.springsource.org/spring/docs/2.5.x/reference/view.html) jika ingin mengetahui lebih lanjut. Untuk contoh pada artikel ini saya akan mencoba menggunakan class org.springframework.web.servlet.view.ResourceBundleViewResolver.

Langsung ke contoh saja, silahkan ikuti langkah2 berikut:

  1. Tambahkan javax.servlet-jstl.jar ke folder lib. link bisa diambil di sini.
  2. Edit tjong-servlet.xml
    <?xml version="1.0" encoding="UTF-8"?>
    
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    
    <!-- the application context definition for the springapp DispatcherServlet -->
    
    <!-- Contoh Pada Episode 1 -->
    <!-- <bean name="/hello.asik" /> -->
    
    <!-- Contoh Pada Episode 2 -->
    <context:component-scan base-package="com.firstProgram.web"/>
    
    <!--Kesalahan pada contoh Gery, see the comment below-->
    <!--<bean id="viewResolver"
    p:basename="views"/>-->
    <bean id="viewResolver"
    p:basename="view"/>
    
    </beans>
    

    *edited 21 March 2011: thanks to Gery

  3. buat Source Folder (selanjutnya untuk file-file configurasi sebaiknya disatukan saja di dalam folder ini) – pada saat build akan di-compile ke dalam Classpath. Caranya klik kanan nama Project – New – Source Folder. Beri nama resources
  4. buat file view.propertiesdalam folder resources yang baru saja anda buat.
    pages/hello.url = /WEB-INF/pages/hello.jsp
    pages/hello.class= org.springframework.web.servlet.view.JstlView
    
  5. pindahkan folder pages menjadi di dalam folder WEB-INF. (Untuk alas an keamanan).
  6. Edit HelloController.java
    package com.firstProgram.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import java.io.IOException;
    
    @Controller
    public class HelloController{
    
    	@RequestMapping (value="/hello.asik", method=RequestMethod.GET)
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            return new ModelAndView("pages/hello");
        }
    }
    
  7. Testing aplikasi anda. http://localhost:8080/firstProgram/hello.asik. Seharusnya tidak ada perubahan pada tampilan nya, yang berubah hany konfigurasi di belakang layarnya saja.

Spring Web MVC – Quick Start with Eclipse (Episode 1)


Sebelum anda mulai mengikuti tutorial di bawah, ada beberapa hal yang harus dipersiapkan:

  1. Tau cara Start New (Dynamic Web) Project menggunakan Eclipse. Jika belum tahu silahkan baca artikel ini.
  2. Download beberapa jar yang dibutuhkan:
  • spring-2.5.6.jar (untuk contoh ini saya masih menggunakan versi 2.5.6) – download disini
  • spring-webmvc-2.5.6.jar, download disini.
  • commons-logging.jar. download disini.

Ketiga jar diatas adalah minimal untuk memulai membuat Web menggunakan Spring MVC. Tutorial lainnya menggunakan Spring MVC dapat dengan mudah anda jumpai di internet, untuk tutorial yang saya buat ini – saya usahakan mudah dimengerti untuk pemula yang belum pernah menggunakan framework dalam pemrograman nya.

Agar pembelajaran lebih mudah – saya coba tampilkan dulu hasil akhir yang diinginkan. Perhatikan gambar di bawah:

To the point saja. Silahkan ikuti langkah-langkah di bawah:

  1. Jalankan aplikasi Eclipse anda. (Pada contoh ini saya menggunakan Eclipse 3.4.0)
  2. Buat New Project dengan nama firstProgram
  3. Buat package com.firstProgram.web (untuk selanjutnya Class Controller akan dimasukkan ke dalam package ini.)
  4. Edit web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
     <display-name>firstProgram</display-name>
    
     <servlet>
     <servlet-name>tjong</servlet-name>
     <servlet-class>
     org.springframework.web.servlet.DispatcherServlet
     </servlet-class>
     <load-on-startup>1</load-on-startup>
     </servlet>
     <servlet-mapping>
     <servlet-name>tjong</servlet-name>
     <url-pattern>*.asik</url-pattern>
     </servlet-mapping>
    
     <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>
    </web-app>
    
  5. Copy kan 3 buah jar yang sudah anda download ke dalam folder /WEB-INF/lib
  6. Perhatikan pada web.xml, disitu anda sudah menulis nama servlet anda adalah tjong, yang kebetulan adalah nama saya. :p dan menggunakan class org.springframework.web.servlet.DispatcherServlet. Pada spring, adalah suatu keharusan untuk membuat file xml dengan format nama <nama servlet yang di deklarasikan>-servlet.xml, fungsinya adalah mengatur settingan servlet anda.
  7. Buat file dengan nama tjong-servlet.xml di dalam folder WEB-INF
    <?xml version="1.0" encoding="UTF-8"?>
    
    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:p="http://www.springframework.org/schema/p"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    
     <!-- the application context definition for the springapp DispatcherServlet -->
    <bean name="/hello.asik" class="com.firstProgram.web.HelloController"/>
    
    </beans>
    
  8. Buat folder pages di dalam folder WebContent. Untuk selanjutnya setiap file jsp yang anda buat sebaiknya disatukan di dalam folder ini.
  9. Buat file hello.jsp di dalam folder pages
    <html>
     <head><title>Example :: First Spring MVC Application</title></head>
     <body>
     <h1>Example - Spring Application</h1>
     <p>For my nakama.</p>
     </body>
    </html>
    
  10. Terakhir adalah membuat class Controller, buat file HelloController.java pada package com.firstProgram.web
    package com.firstProgram.web;
    
    import org.springframework.web.servlet.mvc.Controller;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import java.io.IOException;
    
    public class HelloController implements Controller {
    
     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    
     System.out.println("Andreas");
     return new ModelAndView("pages/hello.jsp");
     }
    
    }
    
  11. Coba jalankan aplikasi anda pada server.  Di address bar masukkan alamat berikut: http://localhost:8080/firstProgram/hello.asik.  Hasilnya kira-kira adalah seperti ini.

Daftar Pusataka:

  1. Spring MVC step by step. link

NOTE: mohon maaf sebelumnya karena ada kesalahan pengetikan yang cukup fatal pada saat publish Dec 17, 2010, Dan sudah diperbaiki per tanggal Dec 20, 2010.