Spring Web MVC – How to add picture and css (Episode 6)


OK. Kita akan mundur agak jauh pada episode kali ini. Kita akan menggunakan kembali Project yang telah kita buat pada episode 1 saja (NOTE: jika menggunakan episode yang selanjutnya juga tidak apa-apa, tinggal disesuaikan saja). Bagi yang blom mengerti tentang episode 1 itu apa, silahkan baca link https://andreastjong.wordpress.com/2010/12/17/spring-web-mvc-%E2%80%93-quick-start-with-eclipse-episode-1/ , akan sangat membantu sekali dalam pemahaman artikel ini.

Download beberapa jar yang dibutuhkan:

  1. standard-1.1.2.jar – silahkan di download di http://repo1.maven.org/maven2/taglibs/standard/1.1.2/standard-1.1.2.jar

Pada contoh ini saya coba membuat New Project dengan nama secondProgram. Dengan isi + structure yang sama dengan contoh pada episode 1. Target yang kita inginkan adalah membuat halaman Web seperti contoh di bawah:

Saya anggap kalian sudah mengikuti semua langkah2 yang ada pada Episode1. Untuk selanjutnya kita akan menambahkan file gambar dan css ke dalam halaman hello.jsp (Mohon maaf kalau gambar dan css yang saya gunakan kurang bagus, takut terbentur dengan masalah license nih. :p). Silahkan ikuti langkah2 berikut:

  1. Download library tambahan di atas, lalu masukkan ke dalam folder library project
  2. Buat folder images pada folder WebContent, lalu copy kan. Image anda ke dalam folder tersebut. (NOTE: tolong diperhatikan, nama file dan ext nya, sebaiknya dibuat menjadi huruf kecil semua, karena jstl case sensitive)
  3. Buat folder css pada folder WebContent, lalu create new file – “style.css “. Yang isinya sebagai berikut:
    * { font: 11px verdana, Verdana,DIN-Light sans-serif; }
    
    body {
    	margin:0;
    	padding:0;
    	background:#f9f9f9;
    }
    
  4. Edit hello.jsp (untuk nama file gambarnya, silahkan disesuaikan saja dengan nama file gambar anda)
    <!DOCTYPE html PUBLIC
    	"-//W3C//DTD XHTML 1.1 Transitional//EN"
    	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <html>
    <head>
    	<title>Example :: First Spring MVC Application</title>
    	<link href="<c:url value="/css/style.css"/>" rel="stylesheet" type="text/css" />
    </head>
    
    <body>
    	<h1>Example - Insert an Image</h1>
     	<p>For my nakama.</p>
    
     	<img alt="My Bike" src="<c:url value="/images/bike.png"/>">
    </body>
    </html>
    
    
  5. Coba jalankan aplikasi anda pada server. http://localhost:8080/secondProgram/hello.asik
Advertisement

Simple JDBC Connection for AS400


Tujuan artikel ini adalah memberikan contoh bagimana membuat sebuah Simple Class untuk JDBC Connection + Menjalankan Query yang sangat simple sekali. Kenapa harus AS400? Karena contoh yang menggunakan MySQL atau MS SQL Server atau ORACLE sudah banyak sekali dipasaran. Apa sih AS400 itu? AS400 adalah bla bla bla (silahkan di klik saja bla bla bla nya).

Persiapan:

  1. Download jar yang dibutuhkan: jt400-full-6.0.jar, bisa di download disini.

Jika anda sudah pernah masuk ke dalam console – AS400 tentu akan sangat membantu sekali. Jika anda belom pernah masuk ke console – AS400, jangan berkecil hati dulu, karena apa yang saya bicarakan nanti mirip sekali dengan Query Analyzer pada MS SQL Server 2000.  Tujuan dari program ini adalah menjalankan query pada Menu STRSQL di AS400 atau Query Analyzer di MS SQL Server 2000.

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. Klik Kanan pada Package Explorer. Lalu pilih New – Project – Java Project. Beri nama project nya “simpleJDBC”.
     

  3. Download jar di atas.
  4. Klik kanan project nya, pilih properties
  5. Pilih Java Build Path – Tab Libraries – Pilih Add External JARs. Cari file jar yang baru saja di download.
  6. Klik kanan “src” lalu pilih New – package. Beri nama “com.tjong.andreas”
  7. Klik kanan package “com.tjong.andreas” lalu pilih New – Class.  Beri nama: SimpleJDBCAS400. Jangan lupa “public static void main(String[] args)”-nya dicentang.
  8. Tulis code seperti di bawah:
    package com.tjong.andreas;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class SimpleJDBCAS400 {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		/* Ini nanti diganti - disesuaikan dengan kondisi anda*/
    		String server = "NAMA_SERVER";
    		String userId = "USERID";
    		String password = "PASSWORD";
    
    		Connection conn = createConnection(server, userId, password);
    		Integer result = getData(conn);
    
    		System.out.println("RESULT COUNT = " + result);
    
    		closeConnection(conn);
    	}
    
    	public static Connection createConnection(String server, String userId, String password){
            String driver = "com.ibm.as400.access.AS400JDBCDriver";
            String url = "jdbc:as400://"+server;
            try{
            	Class.forName(driver);
            	return DriverManager.getConnection(url,userId,password);
            }
            catch(Exception e){
            	e.printStackTrace();
            	return null;
            }
    	}
    
    	public static void closeConnection(Connection conn){
    		try{
    			conn.close();
    		}
    		catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    
    	public static Integer getData(Connection conn){
    		Integer output = 0;
    
    		Statement stmt = null;
    		ResultSet rs = null;
    
    		/* Ini nanti diganti - disesuaikan dengan kondisi anda*/
    		String query = "SELECT COUNT(1) AS TOTAL FROM NAMA_LIBRARY.NAMA_TABLE ";
    		try{
    			stmt = conn.createStatement();
    			rs = stmt.executeQuery(query);
    		    rs.next();
    		    output = rs.getInt("TOTAL");
    		}
    		catch(Exception e){
    			System.out.println("Error Running Query");
    			System.out.println("Error: " + e.getMessage());
    		}
    		finally{
    			try{
    				rs.close();
    				stmt.close();
    			}
    			catch(Exception e){
    				System.out.println("Error Closing statement");
    				System.out.println("Error: " + e.getMessage());
    			}
    		}
    		return output;
    	}
    }
    
    
  9. Testing Program anda. Caranya klik kanan Class “SimpleJDBCAS400”.

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.