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.

Advertisements

5 thoughts on “Spring Web MVC – Create Log File (Episode 3)

  1. mas yang web.xml dan logback.xml memang seperti itu yah? ada yg salah tidak mas, msh ada errornya mas. tolong dicek mas. sya lg belajar spring nih… 🙂

    • saya coba jalankan kan, tampilan tidak sesuai dengan di atas, letak nya masih berantakan.css nya ga jalan.waktu sya input sya tekan tombol next tidak terjadi apa2.kira2 apa yah?thanks

  2. hi Andreas…
    saya sudah ikutin langkah2 nya.. tapi keknya ada 1 yang kurang lagi… hehe… maap yah… harus ada 1 fungsi lagi sperti nya di HelloController nya… seperti di bawah ini ( maaf saya menggunakan .do –> terinspirasi dari struts.. hehe..)
    @RequestMapping (value=”/excell.do”, method=RequestMethod.GET)
    public ModelAndView handleRequest2(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    return new ModelAndView(“pages/excell”);
    }

  3. eh… maaf mas… ternyata tidak ada yang kurang.. tadi saya lupa ganti excell.asik nya jadi excell.do di controller nya… hahaha… bodoh nya..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s