You are on page 1of 52

1

LP TRNH NET TRN JAVA SERVLETS


Gii thiu v cu trc

Ni dung
2

Applet Servlets, , JSP Sockets programming RMI URL RMI, JDBC

Applet
3

Chng trnh GUI chy trn web browser Java bytecode y c ti n t web server Vn v c ch bo mt
Sandbox
M

Java bytecode cha c kim th trc khi chy Khng kim tra c tin cy ca m chy

Servlets
4

Khng phi l chng trnh GUI Khi to trang g web ng, g, tr li li nhng gy yu cu ca web JSP: Java Server Pages
L

nhng phng php khc nhau khi to servlets. servlets

Lp trnh mng
5

L s giao tip gia cc tin trnh Cc cch tip cn khc nhau:


Mc Tip

thp thng qua API: sockets


phi hiu r hnh thc mng, a ch

C n

cn hng i tng: RMI, CORBA Tip cn trn c s hng phc v: URL

Sockets
6

Sockets API thng c s dng nhiu trong lp trnh API trn C Socket l s giao tip tru tng im cui Cc loi sockets khc nhau:
Stream

(kt ni qua stream byte) Datagram D t (cc ( messages c lp) )


S dng sockets cn phi hiu r v cc tng kt ni mng OSI, a ch mng, hng i

Java sockets
7

Sockets trong Java n gin hn trong C


Che

giu chi tit API c s dng thch hp nht vi TCP/IP


Cc i tng khc nhau c s dng cho cc kiu giao tip mng khc nhau:
Socket

(Stream Client) ServerSocket (Stream Server) DatagramSocket D t S k t (M (Message oriented) i t d)

Socket v ServerSocket (trn giao ti ip TCP/IP)


Thit lp kt ni ngang hng Socket cung g cp I/O stream lin kt vi kt ni


S

dng phng thc I/O ca Java

Xut hin ngoi l mi l vn kh gii quyt Nn s dng khng nhiu qu mt stream

DatagramSocket v D DatagramPacket P k (UDP)


Giao tip hng thng tin


Trao

i thng tin, gi v nhn Nm trong Java I/O


Cc hn ch
Khng

tin cy Hng i khng c m bo Nhn i thng tin c th xy ra Cn hiu rt r v giao i th hc mng s dng

Socket class
10

Class m t v socket To mt socket


Socket(InetAddress

address, int port) Socket(String host, host int port) Socket(InetAddress address, int port, InetAddress localAddr InetAddress, localAddr, int localPort) Socket(String host, int port, InetAddress, localAddr int localPort) localAddr, Socket()

(tip)
11

Ly thng tin v mt socket

InetAddress getInetAddress() : tr v a ch m socket kt ni n. int getPort() : tr v a ch m socket kt ni n. InetAddress getLocalAddress() : tr v a ch cc b. int getLocalPort() : tr v a ch cc b.

S dng Streams

public OutputStream getOutputStream() throws IOException - Tr v mt output stream cho vic vit cc byte n
socket ny. y

public InputStream getInputStream() throws IOException - Tr v mt input stream cho vic c cc byte t
socket ny. y

V d - kt ni n webserver
12

import java.net.*; java net *; import java.io.*; public class getSocketInfo { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { try { Socket theSocket = new Socket(args[i], 80); System.out.println("Connected to " + theSocket getInetAddress() + theSocket.getInetAddress() " on port " + theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of " + theSocket getLocalAddress()); theSocket.getLocalAddress()); }

Lp trnh internet
13

Tt c im cui c phn bit bi 3 loi sau:


Cng

giao tip UDP/TCP S cng g ( c lp vi service) ) a ch IP


IP

ca ngi s dng IP mng

Java Sockets v IP
14

Lp InetAddress Phng g thc:


static

InetAddress getByName(String); static InetAddress getLocalHost(); byte getAddress(); String getHostAddress(); String getHostName();

TCP client/server
15

Client s dng i tng Socket


C n

xc nh a ch server

a

ch IP/hostname v s cng Lin kt stream vi giao tip


Server s dng i tng ServerSocket


C n

phi xc nh s cng server Nhn kt ni mi


Kt

ni mi to i tng Socket

V d - in IP ca locahost
16

import java.net.*; java net *; public class HostInfo { public static void main(String args[]) { H tI f h HostInfo host t = new H HostInfo(); tI f () host.init(); } public void init() { try { InetAddress myHost = InetAddress getLocalHost(); InetAddress.getLocalHost(); System.out.println(myHost.getHostAddress()); System.out.println(myHost.getHostName()); } catch t h (U (UnknownHostException k H tE ti ex) ) { System.err.println("Cannot find local host"); } } }

V d - ly IP ca local/remote host
17 1. 2. 3. 4. 5. 6 6.

public class Sample1 { public static void main (String[] args) { try { InetAddress localAddr = InetAddress.getLocalHost(); System.out.println( "Local Host Address (Host/IP): " + localAddr.toString() localAddr toString() ); InetAddress remoteAddr = InetAddress.getByName("www.vnn.vn"); System.out.println( "Web Server IP: " + remoteAddr.toString() ); } catch (UnknownHostException ex) {ex.printStackTrace(); }// end d main i }// End class }

7. 8. 9. 10 10. 11. 12. 13. 14.

V d v Talk client/server
18

Lp Talker
c

phn lung c stream vo v a stream ra


Lp TalkServer
To

ServerSocket, i s kt ni t client To 2 i tng Talker v chy chng


Lp TalkClient
To

Socket, kt ni vi server To 2 i tng Talker v chy chng

RMI Remote method invocation


19

tng to i tng Java thc thi mng Server p phi bao gm code, , theo di requests q
Ti

mt s a ch/hostname Gi phng thc request request, v tr v kt qu Tun t ha


Cli t ph Client hi to i tng t xa

V d RMI code
20

SimpleRMI, AlternativeSimpleRMI
Cung

cp t xa v thm/bt i tng To i tng server phc v client


SortRMi
To

phng thc ngn t xa C th d dng nhn/gi cc kiu i tng phc

URL Uniform Resource Locator


21

a ch internet world wide web Lp URL ca Java


Xy

dng v phn tch cc URL To i tng URLConnection


C

th tng tc vi server

To

kt ni ti URL
c d liu t server

InputStream

Mt s phng thc URL


22

String getHost(); String gg getPath(); (); String getQuery(); InputStream openStream(); URLConnection openConnection();

Tm v in trang web
23

try { URL u = new URL("http://www.google.com"); ( p g g ) BufferedReader r = new BufferedReader( new InputStreamReader( u u.openStream())); openStream())); String s; while ( (s = r.readLine()) != null) y p ( ) System.out.print(s); } catch (... I/O and URL Exceptions ..

24

Servlets v JSP

Gii thiu
25

JSP l cng ngh script chy pha web server ca hng Sun ging nh ASP/PHP JSP dng d ngn ng Java J cho h cc pht ht biu nh h if, if for, f dowhile, while, biu thc, li gi hm. v phn bit ch HOA v thng. ng Hin JSP c th chy trn nhiu Web server khc nhau t Tomcat, Apache, Jrun, JavaWebServer,... Min l chng h tr Servlet Engine. server nhn bit c file no l JSP, , ta lun dng g extension qui nh theo cu hnh (mc nh l *.jsp).

Lp trnh web v Java


26

Java web server


27

Server bao gm JVM


Java

sn sng thc thi, khng cn khi ng vi mi request gi n JVM c mt s i tng servlets


Khi

request gi n, phng thc i tng servlet c gi bt request

N u

request gi n c lp servlet mi, lp c th c load trc tip To lp vi m rng


javax.servlet.http.HttpServlet

To servlet
28

To lp s dng
javax.servlet.http.HttpServlet

Vit phng thc


init()

c gi khi i tng c khi to doGet() / doPost() c gi khi web request c gi n destroy() c gi khi hy i tng

V d Servlet
29

public bli class l H HelloServlet ll S l t extends t d Htt HttpServlet S l t{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set the content type of the response response.setContentType("text/html"); C ( / ) // get a writer associated with the response stream. PrintWriter out = response.getWriter(); response getWriter(); out.println("<HEAD><TITLE>Hello</TITLE></HEAD>"); out.println("<BODY><p>Hello Client</p></BODY>"); out.close(); } }

JSP Java Server Pages


30

To m HTML bao gm m Java trong


Khng

cn nh ngha lp, ch cn trn m trong

HTML

File .jsp j p c convert sang g servlet mt cch t ng

Cu trc trang JSP


31

Mt trang JSP l 1 file *.jsp , v d: hello.jsp Vit mt trang JSP bng bt k trnh son tho no k c Notepad, N t d ri lu li vi t tn * *.jsp. j JSP thng dng cc i tng Java chnh quy x l cc gii thut phc tp. p Cc i tng java ny s c ng gi dng JavaBean. on script JSP c ng trong tag <% .... %> %>. Biu thc dng: <%= (exp) %> tng ng vi <% out print( exp ) %> out.print(

v d: <%= (5 + 3) %> tng ng vi <% out.println( 5 + 3 ) %>

Cc i tng c sn trong JSP


32

i tng request i t ng g response p i tng out i tng application i tng session

V d JSP
33

<%@ %@ page import="java.util.*" i t "j til *" % %> <HTML> <HEAD><TITLE>JSP Demo</TITLE></HEAD> <BODY> <%! Date theDate = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return theDate; } %> Hello! The time is now <%= getDate() %> </BODY> </HTML>

V d - data.jsp data jsp


34 1. 2. 3. 4. 5. 6 6.

7. 8. 9. 10. 11.

<HTML> <HEAD> <TITLE>JSP Example</TITLE> </HEAD> <BODY BGCOLOR="ffffcc"> <CENTER> <H2>Date and Time</H2> <% /*Begin JSP scriptJava script Java code sampleComment sample Comment */ java.util.Date today = new java.util.Date(); out println("Today's date is: "+today); out.println("Today's %> </CENTER> </BODY> </HTML>

Cc th script trong JSP


35

Khi <% % ... % %>


Dng nm bt cc khai bo, biu thc, to i tng, gi phng p g thc VD: <% out.println(<h1> Hello to JSP world </h1>); %>

Th <%@page %@ ... % %>


Dng khai bo ngn ng script, cc pht biu import. VD: %@page language="java" a guage ja a import="java.util.*; po t ja a ut ; ja java.sql.*" a sq %

Th <%! .... %>


Dng khai bo cc bin, cc phng thc cp trang JSP. VD: <%! int x = 10; double y = 2.0; %>.

(tip)
36

Th <%= ... %>


Dng

cho cc biu thc.VD: <%= a+b %> or <%= new java.util.Date() %>

Th <%@ include ... %>


Dng

chn cc file JSP khc khc. VD: <%@include file="copyright.html" %>

Lp JApplet
37

S dng vit applet Appletviewer pp s dng g chay y applet pp m khng cn web browser a applet vo trong HTML
<APPLET code=classname code codebase=optional_path_to_classes width=200 height=200> Alternate text </APPLET>

38

JDBC

Kin trc tng qut


39

40

Nhng bc c bn s dng d b database trong J Java


1. 2. 3. 4. 5.

To kt ni connection To c p php p JDBC Statements Chy c php SQL Nhn kt qu ResultSet ng kt ni

1 To kt ni - connection 1.
41

import i t java.sql.*; j l* Np driver ca d liu cung cp Class.forName( Class forName("oracle oracle.jdbc.driver.OracleDriver jdbc driver OracleDriver"); ); Phng thc ng np driver cho c s d liu Oracle DriverManager.registerDriver(new g g ( com.microsoft.jdbc.sqlserver.SQLServerDriver()); To kt ni - connection Connection C ti con = D DriverManager.getConnection( i M tC ti ( "jdbc:oracle:thin:@oracle-prod:1521:OPROD", username, passwd); Connection connection = DriverManager.getConnection( "jdbc:microsoft:sqlserver://<Host>:1433",username,passw d);

2 To c php - JDBC statement 2.


42


Statement stmt = conn.createStatement() ;


Khi to i tng Statement dnh cho gi c php SQL ti c s d liu:
1. 2. 3. 4 4.

Chun b Statement Lin kt tham s Cng vo trong gi Lp li bc 2 v 3 n khi truy cp vo tng phn t ca mt bng Khi ng (chy)

5.

V d
43

Statement stmt = conn.createStatement( ); int[] rows; for(int i=0; i<accts.length; i++) { accts[i].calculateInterest( ); stmt.addBatch("UPDATE account " + "SET balance = " + accts[i].getBalance( ) + "WHERE acct_id = " + accts[i].getID( []g ( )); } rows = stmt.executeBatch( stmt executeBatch( );

3 Chy c php SQL 3.


44

String St i createLehigh t L hi h = "Create C t t table bl Lehigh " + "(SSN Integer not null, Name VARCHAR(32), ( ), " + "Marks Integer) g )"; stmt.executeUpdate(createLehigh); String insertLehigh = "Insert into Lehigh values l + "(123456789,abc,100) (123456789 b 100)"; stmt.executeUpdate p (insertLehigh); ( g );

4 Nhn kt qu - ResultSet 4.
45

S String queryLehigh h h = "select l * from f Lehigh h h"; ResultSet rs = Stmt.executeQuery(queryLehigh); while (rs.next()) { int ssn = rs.getInt("SSN"); String name = rs.getString("NAME"); int marks = rs.getInt( g ("MARKS"); }

5 ng kt ni 5.
46

stmt.close(); conn.close(); ();

Tin trnh v JDBC


47

JDBC cho h php h SQL statements t t t nhm h li th thnh h nhm h trong mt tin trnh ring bit iu khin tin trnh c thc hin bi i tng Connection, kiu ngm nh l auto-commit, tc l mi mt sql statement c i x nh mt tin trnh C th tt ch auto-commit vi conn.setAutoCommit(false); V c th bt li vi conn.setAutoCommit(true); tA t C it(t ) Mt khi auto-commit b tt, khng c SQL statement no c a ra cho n khi thc hin conn.commit(); conn commit(); Ti thi im tt c s thay i c thc hin bi SQL statements s l bt bin trong g c s d liu

Bt li vi ngoi l Exceptions
48

Chng trnh c th ly li v li trong g thi p ph hp c s d liu trng Nu c php try nm c ngoi l, n c th bt ngoi l vi c php catch S dng finally {} dn dp ngoi l C th quay li tin trnh catch { } hoc ng kt ni ti c s d liu v lm sch cc quan h trong khi lnh finally {}

49

Mt cch khc kt ni c s d liu (JDBC-ODBC) (JDBC ODBC)

Metadata trong c s d liu


50

Kt ni ca c s d liu cho h php h cung cp cc thng tin biu th cc bng thng qua c php SQL SQL, dung lng ca kt ni, i cc quy trnh kt ni Cc thng tin c to nn bi i tng DatabaseMetaData

V d Metadata
51

Connection con = . ; DatabaseMetaData dbmd = con.getMetaData(); String catalog = null; String schema = null; String table = sys%; String[ ] types = null; ResultSet rs = dbmd.getTables(catalog , schema , table , types );

V d JDBC - metadata
52

public bli static t ti void id printRS(ResultSet i tRS(R ltS t rs) ) th throws SQLE SQLException ti { ResultSetMetaData md = rs.getMetaData(); // get number of columns int nCols = md.getColumnCount(); // print column names for(int i=1; i < nCols; ++i) System.out.print( md.getColumnName( i)+","); / / output resultset while ( rs.next() ) { for(int i=1; i < nCols; ++i) System.out.print( rs.getString( i)+","); System.out.println( rs.getString(nCols) ); } }

You might also like