JSP

66
Intro to JSP Intro to JSP (J2EE) (J2EE) E-Technology Center Widodo.com

Transcript of JSP

Page 1: JSP

Intro to JSPIntro to JSP(J2EE)(J2EE)

E-Technology Center

Widodo.com

Page 2: JSP

Kinds of ApplicationKinds of Application• Java Application : run under DOS • Java Swing : run under DOS with GUI• Applet : run under browser• Servlet : run on web server• JSP : run on web server to make web

more dynamic

Page 3: JSP

Java Server Pages (JSP)Java Server Pages (JSP)• To make easier management of dynamic web

with separates presentation tier and business/logic tier.

Different between Servlet and JSP :• Servlet is for changing traditional CGI, executed

on server and sending response to browser• JSP separates content of dynamic web and static

web and separates logic and presentation tier.• JSP using bean

Page 4: JSP

Web Application Web Application

Page 5: JSP

Creating JSP ApplicationCreating JSP Application

Page 6: JSP

CodeCode<html><head><title>Halaman JSP Menggunakan NetBeans 6.0</title></head><body><font color=green><h2> Selamat Belajar Aplikasi Enterprise J2EE dan Struts</h2></font><br><hr><font color=#34534><h5> Ikuti segera training J2EE & Struts yang kami adakan

</font></h5><font color=green ><img src="widodo.jpg" width=100 height=120><h4 align=left> Coppyright WWW.Widodo.Com-2008,

HP:08569887384</h4></font><h5> <a href=”www.widodo.com”>www.widodo.com</a></h5><h5> GOEDANGNYA ILMU TI DAN ELEKTRONIKA </h5></body></html>

Page 7: JSP

ResultResult

Page 8: JSP

Multitier ApplicationMultitier Application

Page 9: JSP

ServletServlet

Page 10: JSP

Web ModulWeb Modul

Page 11: JSP

Demo StrutsDemo Struts

Page 12: JSP

Creating JSP Web Creating JSP Web ApplicationApplication

Page 13: JSP

CodeCode<jsp:forward page="Welcome.do"/>

Page 14: JSP

ResultResult

Page 15: JSP

Sql Server 2005 Sql Server 2005

Page 16: JSP

Creating databaseCreating database

Page 17: JSP

Creating login’s tableCreating login’s table

Page 18: JSP

Creating customer’s tableCreating customer’s table

Page 19: JSP

QueryQuery

Page 20: JSP

ODBCODBC

Page 21: JSP

ODBCODBC

Page 22: JSP

Sql Server Connection Sql Server Connection url = "jdbc:microsoft:sqlserver://localhost:1433" ;// membuat exception handling untuk membuat koneksi ke

databasetry {// register driverClass.forName

( "com.microsoft.jdbc.sqlserver.SQLServerDriver" ) ;// mendefinisikan koneksi ke databasecon = DriverManager.getConnection ( url , "sa" ,

"password" ) ;// membuat objek statement atau mendefinisikan sejumlah

metode yang //berhubungan dengan pernyataan SQLst = con .createStatement ( ) ;....

Page 23: JSP

ODBC ConnectionODBC Connectionimport java.sql.*;//paket untuk sqlpublic class CreateCoffees {public static void main(String args[]) {//nama odbc ialah KopiString url = "jdbc:odbc:Kopi";Connection con; //Buat objek Conection

Page 24: JSP

Statement ClassStatement ClassKelas ini biasa digunakan untuk query standar tanpa parameter:

Contoh:String url=”jdbc:odbc:Kopi”;String userID=”sa”;String password=””;Statement DataRequest;ResultSet Results;Connection Db;try {String query=”select * from customers”;DataRequest =Db.createStatement();Results=DataRequest.executeQuery(query);DataRequest.close();

Page 25: JSP

PreparedStatement ClassPreparedStatement ClassSebuah query SQL dapat diprecompilasi dan dieksekusi

menggunakan objek PreparedStatement. Tanda Tanya (?) dapat digunakan sebagai tempat untuk memasukkan nilai.

try { String query=”Select * from Customers where

CustNumber=?”;PreparedStatement pstatement=Db.preparedStatement(query);pstatement.setString(1,”123”);Results=pstatement.executeQuery();

pstatement.close();

Page 26: JSP

Callable Statement ClassCallable Statement ClassObjek CallableStatement digunakan untuk memanggil stored

prosedure dari objek java. Stored procedure ialah sekumpulan sintaks sql yang mempunyai 1 buah nama dan dapat dipanggil oleh program.

Contoh :String ordernumber;try {String query=”{CALL StoredProcSaya (?)}”;CallableStatement cstatement =Db.prepareCall(query);sstatement.registerOutParameter(1,Types.VARCHAR();sstatement.execute();ordernumber=cstatement.getString(1);cstatement.close();

Page 27: JSP

JSP Scripting ComponentsJSP Scripting Components• JSP scripting components

– Scriptlets (delimited by <% and %>)– comments (delimited by <%-- and-%>)– Expressions (delimited by <%= and %>)– Declarations (delimited by <%! And %>)

Page 28: JSP

Simple JSPSimple JSP<html> <body><font color=green><h2> Selamat Datang , tanggal dan waktu sekarang :</h2></font><font color=red> <% System.out.println( "Tanggal sekarang :" ); java.util.Date date = new java.util.Date(); out.println (date); %></h3></font></body></html>

Page 29: JSP

JSP DirectiveJSP Directive<%@ page import="java.net.*" %><html><body>

<% System.out.println( "Tanggal sekarang :" ); java.util.Date date = new java.util.Date();%><h3>Selamat Datang, Waktu saat ini ialah :</h3><h4><% InetAddress a= InetAddress.getLocalHost(); out.println( date ); out.println( "<BR>IP Address kamu " ); out.println( a.getHostAddress()); out.println( "<BR>Nama komputer kamu " ); out.println( request.getRemoteHost());%></h4></body></html>

Page 30: JSP

Include DirectiveInclude Directive• <h1> contoh include directive </h1>• <%@ include file=“included.jsp” %>

• Included.jsp :<%@ page import =“java.util.Date”%>

Page 31: JSP

Include DirectiveInclude Directive<html> <head> <title>Include directive </title> </head> <body> <h1>Contoh Include directive </h1> <%@ include file="/copyright.html" %> </body></html>

Copyright.html :…E-Technology Center 2008…

Page 32: JSP

Standard ActionStandard ActionAction Description <jsp:include> Dynamically includes another resource in a JSP. As the JSP executes, the

referenced resource is included and processed. <jsp:forward> Forwards request processing to another JSP, servlet or static page. This

action terminates the current JSP’s execution. <jsp:plugin> Allows a plug-in component to be added to a page in the form of a

browser-specific object or embed HTML element. In the case of a Java applet, this action enables the downloading and installation of the Java Plug-in, if it is not already installed on the client computer.

<jsp:param> Used with the include, forward and plugin actions to specify additional name/value pairs of information for use by these actions.

JavaBean Manipulation <jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies the

scope of the bean and assigns it an ID that scripting components can use to manipulate the bean.

<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of this action is automatic matching of request parameters to bean properties of the same name.

<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the result to a string for output in the response.

Fig. 25.5 JSP standard actions.

Page 33: JSP

ImplementationImplementation

Page 34: JSP

CodeCode<head> <meta http-equiv = "refresh" content = "5" /> <title>Using jsp:include</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } table, tr, td { font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style>

Page 35: JSP

CodeCode

<%-- include header.html in this JSP --%> <jsp:include page = "header.html" flush = "true" /> </td> </tr> <tr> <td style = "width: 160px"> <%-- include toc.html in this JSP --%> <jsp:include page = "toc.html" flush = "true" /> </td>

Page 36: JSP

CodeCode<% // get client locale java.util.Locale locale = request.getLocale(); // get DateFormat for client's Locale java.text.DateFormat dateFormat = java.text.DateFormat.getDateTimeInstance( java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale ); %> <%-- end script --%> <%-- output date --%> <%= dateFormat.format( new java.util.Date() ) %> </p>

Page 37: JSP

Display DataDisplay Data

Page 38: JSP

codecode<html><title>Latihan JSP dengan JDBC </title><body bgcolor=yellow><font color=blue><h1>Daftar Programmer</h1></font><table border="1" cellpading="5" cellspacing="0" bgcolor=silver

bordercolor=green><tr><td>No</td><td>nama</td><td> Deskripsi</td><td>Aksi</td></tr><%@ page import="java.sql.*"%><% Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");Connection con = DriverManager.getConnection

("jdbc:odbc:Kopi","sa",“kursusjsp");Statement stmt = con.createStatement ();ResultSet rst = stmt.executeQuery ("Select * from programmer");

Page 39: JSP

codecode//baca datawhile(rst.next()){int no=rst.getInt("no");String nama=rst.getString("nama");String deskripsi=rst.getString("deskripsi");out.print ("<tr><td>"+no+"</td>");out.print ("<td>"+nama+"</td>");out.print ("<td>"+deskripsi+"</td>");out.print ("<td><a href=rubahdb.jsp?" + no + ">Rubah Data");out.print ("<a> | <a href =hapusdb.jsp?" + no + ">Hapus Data</a>");out.println ("</td></tr>");}stmt.close();con.close();%></table><br><a href="tambah.jsp"> Tambah Data Programmer </a><font color=green><h4 align=right><i> Copyright e-Technology Center, 2009</i><BR><b> Widodo.com </b></h4></font><img src="sdn.jpg" with=400 height=50> </body></html>

Page 40: JSP

Adding dataAdding data

Page 41: JSP

codecodetambah.jsp:<html><form method="POST" action ="tambahdb.jsp"><h3> Silahkan tambah data </h3><br><H5> No :</h5><input type=text name="id" cols=20></input><H5> Nama:</h5><input type=text name="nama" cols=30></input><h5> Deskripsi: </h5><textarea rows="5" name="TextGanti" cols="42"> </textarea><p><input type="Submit" value ="Tambah data" name="a"><input type="reset" value="Reset" name="b"></p></form></html>

Page 42: JSP

Update DataUpdate Data

Page 43: JSP

codecode<%@ page import="java.sql.*" %><% String kunci=request.getQueryString();String sql= "Select * from programmer where programmer.no = " + kunci;Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");Connection con = DriverManager.getConnection ("jdbc:odbc:Kopi","sa",“kursusjsp");Statement stmt = con.createStatement ();ResultSet rs=stmt.executeQuery(sql);rs.next();%><form method="POST" action="simpandb.jsp"><% out.println ("<h3> Silahkan Update data </h3><br>");%><textarea rows="5" name="nama" cols="22"><%= rs.getString ("nama") %></textarea><textarea rows="5" name="TextGanti" cols="42"><%= rs.getString ("deskripsi") %></textarea><p><% out.println ("<input type=\"hidden\"value=" + kunci + " name=\"kunci\">");%><input type="Submit" value= "Rubah data" name="a"><input type="reset" value="Reset" name="b"></p></form><%stmt.close();con.close();%>

Page 44: JSP

codecode<%@ page import="java.sql.*" %><% String kunci=request.getParameter ("kunci");String nama=request.getParameter("nama");String ganti=request.getParameter ("TextGanti");String sql ="update programmer set nama='" + nama + "', deskripsi='" +

ganti+"' where no="+ kunci;Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");Connection con = DriverManager.getConnection

("jdbc:odbc:Kopi","sa","mautauaja");Statement stmt = con.createStatement ();stmt.executeUpdate(sql);stmt.close();con.close();%><jsp:forward page="programmer.jsp"/>

Page 45: JSP

Login FormLogin Form

Page 46: JSP

codecodeheader.jsp:<%

String driver_sql = "sun.jdbc.odbc.JdbcOdbcDriver"; //driverString nama_server="widodolaptop"; // Nama websiteString namadb="kursus"; // database yang digunakanString user_sql="sa"; // user untuk sql serverString pass_sql=“kursusjsp; // password untuk sql server

java.util.Date tanggal = new java.util.Date();int tgl = tanggal.getDate();int bln = tanggal.getMonth()+1;int thn = tanggal.getYear()+1900;int jam = tanggal.getHours();String hari;if(jam <= 3 || jam >= 20) hari = "Malam";else if(jam > 3 || jam < 11) hari ="Pagi";else if(jam >= 11 || jam <= 16) hari = "Siang";else hari = "Sore";

%>

Page 47: JSP

codecodebuatkoneksi.jsp:<%

Class.forName(driver_sql);String urldb="jdbc:odbc:Kopi";Connection koneksi_sql=DriverManager.getConnection(urldb, user_sql, pass_sql);Statement statement_sql=koneksi_sql.createStatement();ResultSet hasil_query=null;Statement statement_sql2=koneksi_sql.createStatement();

ResultSet hasil_query2=null;%>

Page 48: JSP

codecodelogin.jsp: import="java.sql.*" errorPage="" %><%@include file="header.jsp" %><%@include file="buatkoneksi.jsp" %><%

String idk=request.getParameter("idk");if(idk==null)idk="";String sandi=request.getParameter("sandi");if(sandi==null)sandi="";

hasil_query=statement_sql.executeQuery("select * from login");String idk_sql=null;String sandi_sql=null;boolean login=false;

Page 49: JSP

codecodewhile(hasil_query.next())

{idk_sql=hasil_query.getString("username");sandi_sql=hasil_query.getString("password");if(idk.equals(idk_sql) && sandi.equals(sandi_sql)){

session.setAttribute("idk", idk);login=true;break;

}}

%>

<%

if(login){%>

<jsp:forward page="main.jsp"><jsp:param name="link" value="home" /></jsp:forward>

<%}else

Page 50: JSP

Forward ActionForward Action• <form method=“post” action=“forward.jsp”

• <jsp:forward page=“forward2.jsp”/>

Page 51: JSP

<jsp:useBean><jsp:useBean>• Using java bean for jsp page for separates

presentation and logic tier.• <jsp:useBean id=“name” scope=“scopeName” beanDetails />

Value of scope :page: bean provided for that pagerequest: pages + <jsp:include> and <jsp:forward>session : all jsp page that requested and grouped with

1 sessionapplication : bean provided for all jsp pages.

Page 52: JSP

<jsp:setProperty><jsp:setProperty>• For set properties at bean

<jsp:setProperty name=“beanName” propertyDetails/>

Page 53: JSP

<jsp:getProperty><jsp:getProperty>• For getting properties from bean• <jsp:getProperty

name=“beanName” property=“propertyName”/>

Page 54: JSP

Example EJBExample EJB

Page 55: JSP

Sample Tag ActionSample Tag Action<jsp:useBean id=“ActionTagBean” scope=“page”

class=“WebJ2EE.ActionTagBean”><jsp:setProperty name=“ActionTagBean” property=“*”/></jsp:useBean>

jsp:getProperty name="ActionTagBean" property="nama"/>. </p></h3><h4> <p>Bahasa Pemrograman Favorit Anda adalah : <jsp:getProperty name="ActionTagBean"

property="bahasa"/>.</p></h4><font color=red><h3> <p>Komentar Tentang Bahasa

Pemrograman Favorit Anda:</p></h3>

Page 56: JSP

codecodepackage WebJ2EE;public class ActionTagBean { private String nama; //Property Nama private String bahasa; //Property Bahasa public ActionTagBean() {} //konstruktor

//Method untuk menset property nama public void setNama(String nama) { this.nama = nama; } //Method untuk mengambil nilai property nama public String getNama() { return nama; } //Method untuk menset property bahasa public void setBahasa(String bahasa) { this.bahasa = bahasa; } //Method untuk mengambil nilai property bahasa public String getBahasa() { return bahasa; }

Page 57: JSP

codecode //Method untuk mengambil nilai komentar dr bahasa public String getKomentar() { if (bahasa.equals("Java")) { return "Saya jadi jago OOP karena Java, juga dari buku ini"; } else if (bahasa.equals("C++")) { return "Bahasa C++ kadang memusingkan kita karena Pointer"; } else if (bahasa.equals("VBNET")) { return "Rugi kalau tidak bisa VB.NET"; } else if (bahasa.equals("Visual C#.NET")) { return "Rugi kalau tidak bisa Visual C#.NET"; } else { return "Anda tidak termasuk ahli karena " + bahasa + "."; } }}

Page 58: JSP

Aplikasi KonsultasiAplikasi KonsultasiSupport.html:<form action="techSupport.jsp" method="POST"> <table align="center" width="100%" cellspacing="2" cellpadding="2"> <tr> <td align="right">Email:</td> <td><input type="text" name="email" align="left" size="25"></td> </tr>.. <select name="software" size="1"> <option value="J2EE">Java to Enterprise Edition</option> <option value="VBNET">Visual Basic.NET</option> <option value="VC#NET">Visual C#.NET</option> </select>

Page 59: JSP

Aplikasi KonsultasiAplikasi Konsultasi

Page 60: JSP

Aplikasi KonsultasiAplikasi Konsultasi

Page 61: JSP

Aplikasi KonsultasiAplikasi Konsultasi

Page 62: JSP

Aplikasi KonsultasiAplikasi KonsultasitechSupport.jsp:<jsp:useBean id="techSupportBean" scope="session"

class="WebJ2EE.TechSupportBean" /><jsp:setProperty name="techSupportBean" property="*"/>

<% techSupportBean.registerSupportRequest(); %>

<% if (techSupportBean.isRegistered()) { %> <jsp:forward page="response.jsp"/><% } else { %> <jsp:forward page="regform.jsp"/><% } %>

Page 63: JSP

Aplikasi KonsultasiAplikasi Konsultasi<%@ page errorPage="/error.jsp" %>

<jsp:useBean id="techSupportBean" scope="session" class="WebJ2EE.TechSupportBean" />

<jsp:setProperty name="techSupportBean" property="*"/>

<% techSupportBean.registerCustomer(); %>

<jsp:forward page="response.jsp"/>

Page 64: JSP

Aplikasi KonsultasiAplikasi Konsultasipackage WebJ2EE;import java.sql.*;public class TechSupportBean { String url="jdbc.odbc.Kopi"; private String email; private String software; private String os; private String problem; private String firstName; private String lastName; private String phoneNumber; private boolean registered; private String driver ="sun.jdbc.odbc.JdbcOdbcDriver"; private String protocol="jdbc.odbc.Kopi";

Page 65: JSP

Aplikasi KonsultasiAplikasi KonsultasiTechSupportBean.java:public void registerSupportRequest() throws SQLException { String insertStatementStr= "insert into supp_requests values (?,?,?,?,?)"; String selectCustomerStr= "select customersjava.fname,customersjava.lname,customersjava.phone from customersjava where

customersjava.email=?"; String updateStatementStr="update seq_no set next_no = next_no +1"; String selectStatementStr="select next_no from seq_no"; try { connection = DriverManager.getConnection ("jdbc:odbc:Kopi","sa","mautauaja"); PreparedStatement insertStatement= connection.prepareStatement (insertStatementStr); PreparedStatement updateStatement= connection.prepareStatement (updateStatementStr); PreparedStatement selectStatement= connection.prepareStatement (selectStatementStr); updateStatement.executeUpdate(); ResultSet rp =selectStatement.executeQuery (); rp.next(); int selanjutnya=rp.getInt(1);

Page 66: JSP

The best UTSThe best UTS• RADIETYA UTAMA• VANNESA RINNY• MICHAEL HANSSON • DENNIS REYNALDO WIDYA