SERVLETS Risanuri Hidayat

Download Report

Transcript SERVLETS Risanuri Hidayat

SERVLETS
Risanuri Hidayat
Pendahuluan
• Servlets adalah teknologi Java untuk
menjawab pemrograman dengan Common
Gateway Interface (CGI)
• Servlets adalah program yang dijalankan
pada Web server, sebagai middle layer
antara request dari web browser (clients)
dan Database atau aplikasi lain pada HTTP
Server
Servlets
• Membaca data yang dikirim oleh user (client)
• Melihat informasi lain tentang request yang datang
bersama-sama pada request HTTP
• Membikin result
membaca database, eksekusi RMI,CORBA, dll
• Membuat format result di dalam suatu document
Biasanya berupa halaman HTML
• Men-set parameter-parameter untuk response
maksudnya menginformasikan type document yg akan
dikirim sebagai response, men-set cookies, meng-cache
parameter, dll
• Mengirim response ke client
bisa berupa document html, gif, zip, dll.
Kelebihan Servlets
• Efficient
JVM selalu siap sedia menjalankan setiap
request yang datang dengan threadnya
• Convenient
Dijalankan di Java. Jika kita telah paham
pemrograman Java, Servlets akan sangat
mudah dipahami
Kelebihan Servlets
• Powerful
Mensupport hal-hal yang sulit dilakukan dengan
CGI biasa, misal komunikasi langsung ke Web
Server, translate URL, sharing resources dengan
mudah
• Portable
Ditulis dengan Java dan mengikuti standart API,
sehingga dapat dipasang di berbagai server tanpa
perubahan apapun. Contoh server : Apache, IIS,
Weblogic, I-planet, dsb.
Kelebihan Servlets
• Secure
Pemrograman dengan Java memungkinkan
servlets menjadi lebih aman.
• Murah
Tersedia banyak free-cost Web server yang
mendukung Servlets
Instalasi
• Documentasi untuk Servlets dan JSP
tersedia di
http://java.sun.com/products/servlet/
• JBUILDER
Server
• Apache Tomcat
http://jakarta.apache.org/
• JavaServer Web Development Kit (JSWDK)
http://java.sun.com/products/servlet/
• Allaire Jrun
http://www.allaire.com/products/jrun
• New Atlanta’s ServletExec
http://newatlanta.com
• Sun’s Java Web Server
http://www.sun.com/software/jwebserver/try/
Tomcat
Versi terbaru Tomcat dapat dilihat dan di
download dari
http://jakarta.apache.org/
Hasil down load berupa file :
jakarta-tomcat-4.1.18 4.5 MB
Tomcat
• Instalasi : Just Click It
• Hasil Instalasi : jika tidak ada perubahan
selama instalasi akan berada di
C:\Program Files\Apache Tomcat 4.0.4
• File root terletak di
...\Apache Tomcat 4.0.4\Webapps\ROOT
Tomcat
• Jika instalasi berjalan dengan benar,
hasilnya akan terlihat seperti tampilan di
bawah ini
Tomcat
• Lokasi file index.html terletak di directory
• $CATALINA_HOME/webapps/ROOT/index.html
• $CATALINA_HOME adalah letak root directory
dari hasil installasi. Jika kita tidak melakukan
perubahan apapun selama installasi,
$CATALINA_HOME adalah
C:\Program Files\Apache Tomcat 4.0\
WEB di Tomcat
• Buatlah file html sederhana, sebagai contoh adalah
file yusuf.html sebagai berikut:
<html>
<head>
<title>Yusuf Kurnia Badriawan</title>
</head>
<body>
<p><b>Yusuf Kurnia Badriawan</b></p>
</body>
</html>
WEB di Tomcat
• Kemudian kita buat subdirektori baru di
dalam $CATALINA_HOME yang sejajar
dengan ROOT, misalnya subdirektori test,
sehingga akan terlihat sebagai berikut
$CATALINA_HOME/webapps/test
(atau C:\Program Files\Apache Tomcat
4.0\webapps\test)
WEB di Tomcat
• Letakkan file yusuf.html di subdirectory risanuri. Kemudian kita
buat subdirektori baru di dalam subdirektori risanuri, yang diberi
nama
WEB-INF. Di dalam subdirektori WEB-INF ini kita letakkan file
yang bernama web.xml, yang isinya adalah sebagai berikut,
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
</web-app>
WEB di Tomcat
• Sesungguhnya sampai saat ini kita belum butuh
file web.xml ini, karena Tomcat telah
mendefinisikan web aplikasinya secara global di
subdirectory ..\Apache Tomcat 4.0\conf, juga
dengan nama web.xml. Tetapi sebaiknya kita
buat saja.Kita bisa membuat file web.xml di atas
dengan NotePad atau mengcopy dari
ROOT\WEB-INF.
WEB di Tomcat
• di dalam subdirektori risanuri
($CATALINA_HOME/webapps/risanuri,
atau C:\Program Files\Apache Tomcat
4.0\webapps\risanuri) akan terdapat file-file
dan folder seperti di bawah ini:
..\test\hello.html
\WEB-INF\web.xml
WEB di Tomcat
• Kita jalankan Tomcat (Start Tomcat),
kemudian ketikkan alamat berikut pada
Internet Explorer (atau Netscape)
http://localhost:8080/test/hello.html
WEB di Tomcat
Servlet sederhana
• Sebelumnya, agar servlet kita bisa di-compile oleh Tomcat,
kita harus men-set CLASSPATH pada file autoexec.bat.
Pada Windows 98 atau Windows-Me, kita cari letak file
autoexec.bat ini pada directory WINDOWS. Setelah
ketemu, buka dengan NotePad, kemdian tambahkan
perintah berikut
set CLASSPATH=.;D:\MyServlet;C:\Program Files\Apache
Tomcat 4.0\common\lib\servlet.jar
• Catatan: Kita anggap bahwa D:\MyServlet direkctory kerja
kita saat membuat program-program servlet. Jika anda
memakai directory yang lain, maka perintah itu diganti
dengan directory kerja anda.
Servlet Sederhana
package helloservlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class HelloServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
/**Initialize global variables*/
public void init() throws ServletException {
}
Servlet Sederhana
/**Process the HTTP Get request*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>HelloServlet</title></head>");
out.println("<body>");
out.println("<p><b>Hallo Sayang</b></p>");
out.println("</body></html>");
}
/**Clean up resources*/
public void destroy() {
}
}
Servlet Sederhana
Kembali kita manfaatkan subdirectory ..\risanuri.
Kita buat subdirectory baru dengan nama classes
pada ..\risanuri\WEB-INF. Di dalam subdirectory
..\classes ini kita buat lagi subdirectory dengan
nama helloservlet.
Di dalam listing program di atas nama package-nya
adalah helloservlet, sehingga kita juga harus
membuatkan package (subdirectory) dengan nama
yang sama pada Tomcat (helloservlet).
..\risanuri\WEBINF\classes\helloservlet\HelloServlet.class
Servlet Sederhana
• Setelah HelloServlet.class diletakkan seperti
di atas, kita dapat mengaksesnya dengan
alamat URL:
• http://localhost:8080/risanuri/servlet/helloservlet.HelloServlet
Servlet Sederhana
Jika test menghasilkan hasil yang salah, kemungkinan kesalahan adalah
§
salah ketik pada saat menulis alamat URL di atas,
§
mengganti tanda titik(.) dengan garis miring (/) pada
../helloservlet.HelloServlet.
§
menambahkan extension class di belakang HelloServlet sehingga
menjadi ../helloservlet.HelloServlet.class
Servlet
Two objects are passed to a servlet when it
called by a client:
• ServletRequest - encapsulates the
communication from the client to the server.
• ServletResponse - encapsulates the
communication from the servlet back to the
client
Servlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
The following is a list of available methods of the ServletRequest
interface along with a brief description of their purpose.
• getAttribute(String) - Returns the value of the named attribute of the
request, or null if the attribute does not exist.
• getCharacterEncoding() - Returns the character set encoding for the
input of this request.
• getContentLength() - Returns the size of the request entity data, or -1
if not known.
• getContentType() - Returns the Internet Media Type of the request
entity data, or null if not known.
• getInputStream() - Returns an input stream for reading binary data in
the request body.
Servlet
• getParameter(String) - Returns a string containing the
lone value of the specified parameter, or null if the
parameter does not exist.
• getParameterNames() - Returns the parameter names for
this request as an enumeration of strings, or an empty
enumeration if there are no parameters or the input stream
is empty.
• getParameterValues(String) - Returns the values of the
specified parameter for the request as an array of strings,
or null if the named parameter does not exist.
• getProtocol() - Returns the protocol and version of the
request as a string of the form
<protocol>/<major version>.<minor version>.
• getReader() - Returns a buffered reader for reading text in
the request body.
Servlet
• getRealPath(String) - Applies alias rules to the specified virtual path
and returns the corresponding real path, or null if the translation can
not be performed for any reason.
• getRemoteAddr() - Returns the IP address of the agent that sent the
request.
• getRemoteHost() - Returns the fully qualified host name of the agent
that sent the request.
• getScheme() - Returns the scheme of the URL used in this request, for
example "http", "https", or "ftp".
• getServerName() - Returns the host name of the server that received
the request.
• getServerPort() - Returns the port number on which this request was
received.
HttpServlet
For servlets that extend the HttpServlet class, the
following four methods may be overridden to
cause your servlet to interact with the client.
• doGet() - for handling GET, conditional GET and
HEAD requests
• doPost() - for handling POST requests
• doPut() - for handling PUT requests
• doDelete() - for handling DELETE requests