Vous êtes sur la page 1sur 86

6/2/2012

Networking

Socket Programming
connecting processes

6/2/2012

Introduction to Sockets

Introduction to Sockets
Why Sockets? Used for Interprocess communication. The Client-Server model Most interprocess communication uses client-server model Client & Server are two processes that wants to communicate with each other The Client process connects to the Server process, to make a request for information/services own by the Server. Once the connection is established between Client process and Server process, they can start sending / receiving information. What are Sockets? End-point of interprocess communication. An interface through which processes can send / receive information

Socket

6/2/2012

Introduction to Sockets
What exactly creates a Socket? <IP address, Port #> tuple What makes a connection? {Source<IP address, Port #> , Destination <IP address, Port #>} i.e. source socket destination socket pair uniquely identifies a connection. Example

1343

Client
192.168.0.2 1343

Server
192.168.0.1

80

Client
192.168.0.3

5488

Client
192.168.0.2

Introduction to Sockets
Socket Types STREAM uses TCP which is reliable, stream oriented protocol DATAGRAM uses UDP which is unreliable, message oriented protocol RAW provides RAW data transfer directly over IP protocol (no transport layer) Sockets can use unicast ( for a particular IP address destination) multicast ( a set of destinations 224.x.x.x) broadcast (direct and limited) Loopback address i.e. 127.x.x.x

6/2/2012

A generic TCP application


algorithm for TCP client Find the IP address and port number of server Create a TCP socket Connect the socket to server (Server must be up and listening for new requests) Send/ receive data with server using the socket Close the connection algorithm for TCP server Find the IP address and port number of server Create a TCP server socket Bind the server socket to server IP and Port number (this is the port to which clients will connect) Accept a new connection from client returns a client socket that represents the client which is connected Send/ receive data with client using the client socket Close the connection with client

A generic UDP application


algorithm for UDP client Find the IP address and port number of server Create a UDP socket Send/ receive data with server using the socket Close the connection algorithm for UDP server Find the IP address and port number of server Create a UDP server socket Bind the server socket to server IP and Port number (this is the port to which clients will send) Send/ receive data with client using the client socket Close the connection with client

6/2/2012

Programming Client-Server in Java

Programming TCP Client-Server in Java


All the classes related to sockets are in the java.net package, so make sure to import that package when you program sockets. All the input/output stream classes are in the java.io package, include this also How to open a socket? If you are programming a client, then you would create an object of Socket class Machine name is the machine you are trying to open a connection to, PortNumber is the port (a number) on which the server you are trying to connect to is running. select one that is greater than 1,023! Why??
Socket MyClient; try { MyClient = new Socket("Machine name", PortNumber); } catch (IOException e) { System.out.println(e); }

6/2/2012

Programming TCP Client-Server in Java


If you are programming a server, then this is how you open a socket:

ServerSocket MyService; try { MyServerice = new ServerSocket(PortNumber); } catch (IOException e) { System.out.println(e); }

When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.
Socket clientSocket = null; try { clientSocket = MyService.accept(); } catch (IOException e) { System.out.println(e); }

Programming TCP Client-Server in Java


How to create an input stream? On the client side, you can use the DataInputStream class to create an input stream to receive response from the server:
DataInputStream input; try { input = new DataInputStream(MyClient.getInputStream()); } catch (IOException e) { System.out.println(e); }

The class DataInputStream allows you to read lines of text and Java primitive data types in a portable way. It has methods such as read, readChar, readInt, readDouble, and readLine,. On the server side, you can use DataInputStream to receive input from the client:
DataInputStream input; try { input = new DataInputStream(clientSocket.getInputStream()); } catch (IOException e) { System.out.println(e); }

6/2/2012

Programming TCP Client-Server in Java


How to create an output stream? On the client side, you can create an output stream to send information to the server socket using the class PrintStream or DataOutputStream of java.io:
PrintStream output; try { output = new PrintStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); }

The class PrintStream has methods for displaying textual representation of Java primitive data types. Its write and println methods are important. Also, you may want to use the DataOutputStream:
DataOutputStream output; try { output = new DataOutputStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); }

Many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.

Programming TCP Client-Server in Java


On the server side you can use the class PrintStream to send information to the client.
PrintStream output; try { output = new PrintStream(clientSocket.getOutputStream()); } catch (IOException e) { System.out.println(e); }

Note: You can use the class DataOutputStream as mentioned previously.

6/2/2012

Programming TCP Client-Server in Java


How to close sockets?
You should always close the output and input stream before you close the socket. On the client side:
try { output.close(); input.close(); MyClient.close();

} catch (IOException e) { System.out.println(e); }

On the server side:


try { output.close(); input.close(); clientSocket.close(); MyService.close(); } catch (IOException e) { System.out.println(e); }

HTTP

6/2/2012

Hypertext Transport Protocol\ Language of the Web


protocol used for communication between web browsers and web servers

TCP port 80 RFC 1945

URI,URN,URL
Uniform Resource Identifier
Information about a resource

Uniform Resource Name


The name of the resource with in a namespace

Uniform Resource Locator


How to find the resource, a URI that says how to find the resource

6/2/2012

HTTP - URLs
URL
Uniform Resource Locator
protocol (http, ftp, news) host name (name.domain name) port (usually 80 but many on 8080) directory path to the resource resource name

http://xxx.myplace.com/www/index.html http://xxx.myplace.com:80/cgi-bin/t.exe

HTTP - methods
Methods
GET
retrieve a URL from the server
simple page request run a CGI program run a CGI with arguments attached to the URL

POST
preferred method for forms processing run a CGI program parameterized data in sysin more secure and private

10

6/2/2012

HTTP - methods
Methods (cont.)
PUT
Used to transfer a file from the client to the server

HEAD
requests URLs status header only used for conditional URL handling for performance enhancement schemes
retrieve URL only if not in local cache or date is more recent than cached copy

HTTP Request Packets


Sent from client to server Consists of HTTP header
header is hidden in browser environment contains:
content type / mime type content length user agent - browser issuing request content types user agent can handle

and a URL

11

6/2/2012

HTTP Request Headers


Precede HTTP Method requests headers are terminated by a blank line Header Fields:
From Accept Accept-Encoding Accept Language

HTTP Request Headers (cont.)

Referer Authorization Charge-To If-Modified-Since Pragma

12

6/2/2012

From:
In internet mail format, the requesting user Does not have to correspond to requesting host name (might be a proxy) should be a valid e-mail address

Accept-Encoding
Like Accept but list is a list of acceptable encoding schemes Ex
Accept-Encoding: x-compress;x-zip

13

6/2/2012

User-Agent
Software product used by original client <field> = User-Agent: <product> <product> = <word> [/<version>] <version> = <word> Ex.
User-Agent: IBM WebExplorer DLL /v960311

Referer
For Servers benefit, client lists URL od document (or document type) from which the URL in request was obtained. Allows server to generate back-links, logging, tracing of bad links Ex.
Referer: http:/www.w3.com/xxx.html

14

6/2/2012

Authorization:
For Password and authentication schemes Ex.
Authorization: user fred:mypassword Authorization: kerberos kerberosparameters

ChargeTo:
Accounting information Accounting system dependent

15

6/2/2012

Pragma:
Same format as accept for servers should be passed through proxies, but used by proxy only pragma currently defined is no-cache; proxy should get document from owning server rather than cache

Modified-Since:
Used with GET to make a conditional GET if requested document has not been modified since specified date a Modified 304 header is sent back to client instead of document
client can then display cached version

16

6/2/2012

Response Packets
Sent by server to client browser in response to a Request Packet

Status Header
HTTP/1.0 sp code Codes:
1xx - reserved for future use 2xx - successful, understood and accepted 3xx - further action needed to complete 4xx - bad syntax in client request 5xx - server cant fulfill good request

17

6/2/2012

HTTP Response Headers


Sent by server to client browser Status Header
Entities
Content-Encoding: Content-Length: Content-Type: Expires: Last-Modified: extension-header

Body content (usually html)

Status Codes
200 OK 201 created 202 accepted 204 no content 301 moved perm. 302 moved temp 304 not modified 400 bad request 401 unauthorized 403 forbidden 404 not found 500 int. server error 501 not impl. 502 bad gateway 503 svc not avail

18

6/2/2012

Statelessness
Because of the Connect, Request, Response, Disconnect nature of HTTP it is said to be a stateless protocol
i.e. from one web page to the next there is nothing in the protocol that allows a web program to maintain program state (like a desktop program). state can be maintained by witchery or trickery if it is needed

Maintaining program state Hidden variables (<input type=hidden> Sessions


Special header tags interpreted by the server
Used by ASP, PHP, JSP
Implemented at the language api level

19

6/2/2012

50% - Mtl Already there

Servlets

Evolution of Enterprise Applications - Single Tier


Dumb Terminal 1 Dumb Terminal 2 Dumb Terminal 3
Clients used only for data gathering and output display Mainframe Contains Business logic, Presentation logic and data access

Easy to manage - client side management is NOT required Data consistency is easy and simple to achieve, as all components at one place As application size grows, difficult to maintain and reuse

20

6/2/2012

Evolution of Enterprise Applications - Two Tier (Client/Server)

Database Server

Data Access Layer Business Logic and Presentation Logic Layer

1. 2.

Order fulfillment Application accessing Customer Information Customer care operations accessing same Customer DB

Database product independence Difficult to maintain and update

Evolution of Enterprise Applications - Three Tier

Database Server Business Logic

Presentation Logic Layer

Data Access Layer

Example DART Application

Business logic can change more easily Complexity introduced in the middle tier

21

6/2/2012

Evolution of Enterprise Applications - n Tier

Database Server Thin Clients Presentation Logic Business Logic Data Access Layer

Example - Wep Apps on Sparsh, like Leave System , Harmony

More loosely coupled More reusable Zero client management Complexity in the middle tier

Working of a Web Application


Internet uses Client/Server technology for its working The world wide web uses the Browser as the client software and Web Server as the server software The user types the required URL in the browser The IP Address of the Server is found from the URL The Web Server will be listening in that Server (machine) at Port No 80 The browser connects to Port No 80 of the specified Server Based on the request, the Web Server will deliver the appropriate page to the browser

22

6/2/2012

Web Application model

Client Tier

Middle Tier

Enterprise Information System (EIS) Tier

SQL application Web Container Servlet Servlet JSP Database

browser

File system

Introduction
Servlets are modules that extend request/responseoriented servers, such as Java-enabled web servers. Servlets are to servers what applets are to browsers: an external program invoked at runtime. Unlike applets, however, servlets have no graphical user interface. Servlets can be embedded in many different servers because the servlet API, which you use to write servlets, assumes nothing about the server's environment or protocol. Servlets are portable.

23

6/2/2012

Servlet Basics
It runs inside a Java Virtual Machine on a server host. Unlike applets, servlets do not require special support in the web browser. The Servlet class is not part of the Java Development Kit (JDK). You must download the JDSK (Java Servlet Development Kit). A servlet is an object. It is loaded and runs in an object called a servlet engine, or a servlet container.

Uses for Servlets


Providing the functionalities of CGI scripts with a better API and enhanced capabilities. Allowing collaboration between people. A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Forwarding requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

24

6/2/2012

Generic Servlets and HTTP Servlets


Every servlet must implement the javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes
javax.servlet.GenericServlet javax.servlet.http.HttpServlet

A generic servlet should override the service( ) method to process requests and generate appropriate responses. An HTTP servlet overrides the doPost( ) and/or doGet( ) method.

Servlet Architecture Overview


Servlet

Servlet Interface
methods to manage servlet

GenericServlet
Interface Clas s implements

GenericServlet
implements Servlet

HttpServlet

extends doGet() doPost() service() ...

HttpServlet
extends GenericServlet exposes HTTP-specific functionality

Clas s

UserServlet
extends Class Class Override one or more of: doGet() doPost() service() ...

25

6/2/2012

Generic and HTTP Servlets


Client request response GenericServlet Server

service ( )

Browser request response

HTTPServlet HTTP Server doGet ( ) service ( ) doPost( )

A simple Servlet
public class SimpleServlet extends HttpServlet { /** * Handle the HTTP GET method by building a simple web page. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println("<HTML><HEAD><TITLE>"); out.println(title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); out.println("</BODY></HTML>"); out.close(); } }

26

6/2/2012

Servlet Lifecycle: init()

public void init(ServerConfig cfg) Is called only once


when servlet loads upon clients request

Do not worry about synchronization Perform costly setup here, rather than for each request
open database connection load in persistent data spawn background threads

init()
init() should be completed before starting to handle requests If init() fails, UnavailableException is thrown Invocation process allows to look-up for the initialization parameters from a configuration file
getInitParameter(paramName) method is used to read the parameters

init() parameters are set by the administrator servlet parameters are set by the invocation

27

6/2/2012

Servlet Lifecycle: service()

After the service loads and initializes the servlet, the servlet is able to handle client requests public void service(ServletRequest req, ServletResponse res)
takes Request and Response objects called many times, once per request

Each request calls the service() method


service() receives the client's request, invokes appropriate handling method (doPost(), doGet() etc) and sends the response to the client

service() and concurrency

Servlets can run multiple instances of service() method concurrently


service() must be written in a thread-safe manner it is developers responsibility to handle synchronized access to shared resources

It is possible to declare a servlet as single-threaded


implement SingleThreadModel (empty) interface guarantees that no two threads will execute the service() method concurrently performance will suffer as multiple simultaneous can not be processed

28

6/2/2012

Servlet Lifecycle: destroy()

Servlets run until they are removed When a servlet is removed, it runs the destroy() method The destroy() method is run only once
the servlet will not run again unless it is reinitialized

public void destroy()


takes no parameters afterwards, servlet may be garbage collected

Servlet Lifecycle: destroy() details

Releasing the resources is the developers responsibility close database connections stop threads Other threads might be running service requests, so be sure to synchronize, and/or wait for them to quit Destroy can not throw an exception
use server-side logging with meaningful message to identify the problem

29

6/2/2012

Servlet Lifecycle

30

6/2/2012

Using HTTP Servlet to process web forms

Requests and Responses Methods in the HttpServlet class that handle client requests take two arguments:
An HttpServletRequest object, which encapsulates the data from the client An HttpServletResponse object, which encapsulates the response to the client
public void doGet (HttpServletRequest request, HttpServletResponse response) public void doPost(HttpServletRequest request, HttpServletResponse response)

HttpServletRequest Objects

An HttpServletRequest object provides access to HTTP header data, such

as any cookies found in the request and the HTTP method with which the request was made. The HttpServletRequest object also allows you to obtain the arguments that the client sent as part of the request. To access client data:
The getParameter() method returns the value of a named parameter. If your parameter could have more than one value, use getParameterValues() instead. The getParameterValues() method returns an array of values for the named parameter. (The method getParameterNames() provides the names of the parameters.) For HTTP GET requests, the getQueryString method returns a String of raw data from the client. You must parse this data yourself to obtain the parameters and values.

31

6/2/2012

HttpServletRequest Interface
public String ServletRequest.getQueryString( ); returns the query string of the requst. public String getParameter(String name): given the name of a parameter in the query string of the request, this method returns the value. String id = getParameter(id) public String[ ] GetParameterValues(String name): returns multiple values for the named parameter use for parameters which may have multiple values, such as from checkboxes. String[ ] colors = req.getParmeterValues(color); if (colors != null) for (int I = 0; I < colors.length; I++ ) out.println(colors[I]); public Enumeration getParameterNames( ): returns an enumeration object with a list of all of the parameter names in the query string of the request.

HttpServletResponse Objects
An HttpServletResponse object provides two ways of returning data to the user:
The getWriter method returns a Writer The getOutputStream method returns a ServletOutputStream

Use the getWriter method to return text data to the user, and the getOutputStream method for binary data. Closing the Writer or ServletOutputStream after you send the response allows the server to know when the response is complete.

32

6/2/2012

HttpServletResponse Interface
public interface HttpServletResponse extends ServletResponse: The servlet engine provides an object that implements this interface and passes it into th servlet through the service method Java Server Programming public void setContentType(String type) : this method must be called to generate the first line of the HTTP response:
setContentType(text/html);

public PrintWriter getWriter( ) throws IOException: returns an object which can be used for writing the responses, one line at a time:
PrintWriter out = res.getWriter; out.println(<h1>Hello world</h1>);

Servlets are Concurrent servers


HTTP servlets are typically capable of serving multiple clients concurrently. If the methods in your servlet do work for clients by accessing a shared resource, then you must either:
Synchronize access to that resource, or Create a servlet that handles only one client request at a time.

33

6/2/2012

Handling GET requests


public class BookDetailServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set content-type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter(); // then write the response out.println("<html>" + "<head><title>Book Description</title></head>" + ... ); //Get the identifier of the book to display String bookId = request.getParameter("bookId"); if (bookId != null) { // fetch the information about the book and print it ... } out.println("</body></html>"); out.close(); } ...}

Handling POST Requests


public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set content type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter( ); // then write the response out.println("<html>" + "<head><title> Receipt </title>" + ...); out.println("Thank you for purchasing your books from us " + request.getParameter("cardname") + ...); out.close(); } ... }

34

6/2/2012

The Life Cycle of an HTTP Servlet


The web server loads a servlet when it is called for in a web page. The web server invokes the init( ) method of the servlet. The servlet handles client responses. The server destroys the servlet (at the request of the system administrator). A servlet is normally not destroyed once it is loaded.

Session State Information


The mechanisms for state information maintenance with CGI can also be used for servlets: hidden-tag, URL suffix, file/database, cookies. In addition, a session tracking mechanism is provided, using an HttpSession object.

35

6/2/2012

Cookies in Java
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets. The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servelet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies( ) method. Several cookies might have the same name but different path attributes.

Processing Cookies with Java


A cookie is an object of the javax.servlet.http.cookie class. Methods to use with a cookie object: public Cookie(String name, String value): creates a cookie with the name-value pair in the arguments. import javax.servlet.http.* Cookie oreo = new Cookie(id,12345); public string getName( ) : returns the name of the cookie public string getValue( ) : returns the value of the cookie public void setValue(String _val) : sets the value of the cookie public void setMaxAge(int expiry) : sets the maximum age of the cookie in seconds.

36

6/2/2012

Processing Cookies with Java 2


public void setPath(java.lang.String uri) : Specifies a path for the cookie to which the client should return the cookie. The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories. A cookie's path must include the servlet that set the cookie, for example, /catalog, which makes the cookie visible to all directories on the server under /catalog. public java.lang.String getPath() : Returns the path on the server to which the browser returns this cookie. The cookie is visible to all subpaths on the server. public String getDomain( ) : returns the domain of the cookie. if orea.getDomain.equals(.foo.com) // do something related to golf public void setDomain(String _domain): sets the cookies domain.

doGet Method using cookies


public void doGet(HttpServletResponse req, HttpServletResponse res) throws ServletException, IOExceiption{ res.setContentType(text/html); PrintWriter out = res.getWriter( ); out.println (<H1>Contents of your shopping cart:</H1>); Cookie cookies[ ]; cookies = req.getCookies( ); if (cookies != null) { for ( int i = 0; i < cookies.length; i++ ) { if (cookies*i+.getName( ).startWith(Item)) out.println( cookies*i+.getName( ) + : + cookies*i+.getValue( )); out.close( ); }

37

6/2/2012

Servlet & Cookies Example


See Servlet\cookies folder in code sample: Cart.html: web page to allow selection of items Cart.java: Servlet invoked by Cart.html; it instantiates a cookie object for each items selected. Cart2.html: web page to allow viewing of items currently in cart Cart2.java: Servlet to scan cookies received with the HTTP request and display the contents of each cookie.

HTTP Session Objects


The javax.servlet.http package provides a public interface HttpSession: Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times.

38

6/2/2012

HTTP Session Object 2


This interface allows servlets to
View and manipulate information about a session, such as the session identifier, creation time, and last accessed time Bind objects to sessions, allowing user information to persist across multiple user connections

Session object allows session state information to be maintained without depending on the use of cookies (which can be disabled by a browser user.) Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.

The Session object


Server host

A Session object

servelet engine
servlet

Client host web server


request /response

39

6/2/2012

Obtaining an HTTPSession Object


A session object is obtained using the getSession( ) method of the HttpServletRequest object (from doPost or doGet) public HTTPSession getSession(boolean create): Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null. To make sure the session is properly maintained, you must call this method before the response is committed .
public class ShoppingCart extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletRespnse res) throws ServletException, IOException // get session object HttpSession session = req.getSession(true) if (session != null) { }

The HTTPSession Object methods


public java.lang.String getId( ): returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent. public java.lang.Object getAttribute(java.lang.String name): returns the object bound with the specified name in this session, or null if no object is bound under the name. public java.util.Enumeration getAttributeNames( ): returns an Enumeration of String objects containing the names of all the objects bound to this session. public void removeAttribute(java.lang.String name): removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing.

40

6/2/2012

Session Object example


See Servlet\Session folder in code sample: Cart.html: web page to allow selection of items Cart.java: Servlet invoked by Cart.html; it instantiates a session object which contains descriptions of items selected. Cart2.html: web page to allow viewing of items currently in cart Cart2.java: Servlet to display items in the shopping cart, as recorded by the use a session object in the Cart servlet

For state information maintenance:


hidden form fields cookies the servlets instance variables may hold global data a session object can be used to hold session data

41

6/2/2012

Inter servlet Communication


Inter-Servlet Communication

Allows servlets that are executing on the same Web server to:
Communicate with each other Share resources amongst each other

The RequestDispatcher interface can be used to invoke a servlet from the other

Inter-Servlet Communication (Contd.)

The RequestDispatcher interface:


Can be used to delegate a request to other resources that are existing on the Web server, such as a:
HTML page Servlet JSP page

Encapsulates the URL of a resource that exists in a particular servlet context

42

6/2/2012

Inter-Servlet Communication (Contd.)

The following are few methods that can be used for communication between servlets
Method name getServletContext() Description This method belongs to the interface javax.servlet.ServletConfig public abstract ServletContext getServletContext() This function returns the context of the servlet. getRequestDispatcher() public abstract RequestDispatcher getRequestDispatcher(String urlpath) This method is used to get a reference to a servlet through an URL that is specified as the parameter. The dispatcher that is returned is used to invoke the servlet. If a dispatcher cannot be obtained for the URL specified, this function returns a null.

Method name forward()

Description public abstract void forward(ServletRequest request,ServletResponse response) throws ServletException, IOException This method belongs to the RequestDispatcher interface and can be used to forward a request from one servlet to another. This method must be used when the output is completely generated by the second servlet or the servlet that is invoked.

include()

public abstract void include(ServletRequest request,ServletResponse response) throws ServletException, IOException This function is also used to invoke one servlet from another like the forward() function. However, you can also include the output of the first servlet with the current output.

43

6/2/2012

forward
The forward method of the RequestDispatcher interface may only be called by the calling servlet if no output has been committed to the client. If output exists in the response buffer that has not been committed, it must be reset (clearing the buffer) before the target servlets service method is called. If the response has been committed, an IllegalStateException must be thrown.

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOExcep tion, ServletException { ServletContext context = getServletContext(); RequestDispatcher dispatcher = context.getRequestDispatcher("/myServlet"); dispatcher.forward(req,res); } }

44

6/2/2012

include
The include method of the RequestDispatcher interface may be called at any time. The target servlet has access to all aspects of the request object, but can only write information to the response object as well as the ability to commit a response by either writing content past the end of the response buffer or explicitly calling the flush method of the ServletResponse interface. The included servlet cannot set headers or call any method that affects the headers of the response. Any attempt to do so should be ignored.

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOExcep tion, ServletException { ServletContext context = getServletContext(); RequestDispatcher dispatcher = context.getRequestDispatcher("/myServlet"); dispatcher.forward(req,res); } }

45

6/2/2012

Problem Statement 3.D.2

You need to deposit money into your account. Create a servlet that accepts the account number and pin number. The first servlet should also validate the account number and pass it on to the second servlet. The second servlet should accept the amount to be deposited from the user. The third servlet updates the table and displays the updated balance to the user. In addition, the third servlet also displays the last 20 transactions for that user. The fourth servlet should display the last 20 transactions for that user.

Task List Identify the mechanism Write the client interface Write the code for servlet 1 Write the code for servlet 2 Write the code for servlet 3 Write the code for servlet 4 Compile the servlets Deploy the servlets in J2EE Verify the servlets

46

6/2/2012

Task 1: Identify the mechanism

The RequestDispatcher interface must be used:


To invoke one servlet from the other

The reference to a servlet can be obtained by using:


The servlet context

Task 2: Write the client interface

47

6/2/2012

Task 3: Write code for servlet 1 The first servlet uses the login table to validate the account number and the pin number If the values are valid, an attribute called accountnumber is created and assigned the value entered Else, an error message is displayed to the user The attribute is created by using the setAttribute() method

Task 4: Write the code for servlet 2

The second servlet:


Obtains the account number by using the getAttribute() function Displays a form in which the user can enter the amount to be deposited

The third servlet:


Is invoked on the click of the deposit button in the form

48

6/2/2012

Task 5: Write the code for servlet 3

The third servlet:


Accesses the account number by using the getAttribute() function

Task 6: Write the code for servlet 4

The fourth servlet:


Displays the last 20 transactions that were made by the customers Displays the balance after the previous transaction that was made

49

6/2/2012

Summary
In this lesson, you learned that: RequestDispatcher interface can be used to call one servlet from the other The forward() and the include() method can be used to invoke one servlet from the other

The data, which is common to servlets can be accessed by using the ServletContext interface.

50

6/2/2012

51

6/2/2012

Getting attribute value from ServletContext

JSP

52

6/2/2012

Static Web Pages


A Web page author composes an HTML page, and saves it as an .htm or .html file A user types a page request via URL into the browser, and the request is sent from the browser to the Web server The Web server receives the page request and locates the .htm/.html page in local file system The Web server sends the HTML stream back across the Internet to the client browser The browser interprets the HTML and displays page

Dynamic Web Pages


Content does not always exist before a page is requested Content, at least part of it, is generated upon request For example: the current time on the Web server The e-mail system you use: login page, greeting page, e-mail folders, etc.

53

6/2/2012

Disadvantages of Servlets
Need to be Java programmer Presentation buried in code Cant use web page design tools

Creating Dynamic Web Pages with JSP

JSP is a server-side scripting language that produces Web pages that can be viewed with any browser You can mix regular HTML tags with JSP script in the same JSP page The JSP scripts, if any, are interpreted on the Web server (often called the application server) The content generated by the execution of JSP code is mixed with HTML code and the whole content is sent to the client browser Client never sees JSP part!

54

6/2/2012

Creating Dynamic Web Pages with JSP

JSP file The current date and time on the Web server are: <%= new java.util.Date() %>

Content sent to client The current date and time on the Web server are: Mon Jul 16 10:58:09 PDT 2007

JSP script executes on the Web server and the current date and time are generated

Hello, World JSP Example


<html> <head> <title>Hello World</title> </head> <body> <h1>Hello, World</h1> Its <%= new java.util.Date().toString() %> and all is well. </body> </html>

55

6/2/2012

What Can JSP Do?


Connect to and manipulate a database. Create pages that can display things which will be of interest to a particular user. Collect data from users and return information to a visitor based on the data collected. Modify the content of a Web page, by updating a text file or the contents of a database rather than the HTML code itself.

Access file systems via the Internet so that you can read, write, and update files.
Utilize extensive Java Application Programming Interfaces.

Processing a Request for an HTML Page

56

6/2/2012

Processing a Request for a JSP page

Servlets and JSP


When a JSP page is requested the first time, it is compiled into its corresponding servlet From that point, it is the servlet that handles all corresponding requests

57

6/2/2012

Servlets and JSP

Why Use JSP?


JSP is built on top of servlets, so it has all the advantages of servlets JSP is compiled into its corresponding servlet when it is requested at the first time The servlet stays in memory, speeding response times Extensive use of Java API (Applications Programming Interface) for networking, database access, distributed objects, and others like it Powerful, reusable and portable to other operating systems and Web servers (JSP is a specification, not a product) Separates presentation logic!

58

6/2/2012

Retrieving Form Data


JSP provides request object one of many objects created and maintained by container we use to get info <%= request.getQueryString() %> returns query string exactly as would be appended to URL <%= request.getParameter(Name) %> returns value from Name/Value pair

The Three Kinds of JSP Elements


Directives
do not produce output control translation and compilation of page

Actions
dynamically generate content upon client request some built in actions can create our own xml syntax

59

6/2/2012

The Three Kinds of JSP Elements


Scripts
What we are using now! Allow us to insert code into page <% %> creates a scriptlet <%= %> is an expression

No space between % and = Expression is converted to a String and embedded directly in page

<%! %> declares things that are inserted directly into implementation class in servlet

Form Processing Techniques

60

6/2/2012

Retrieve Form Data


<BODY BGCOLOR="<%= request.getParameter("bgColor")%>"> Hello, <%= request.getParameter("myName") %>: here is your message displayed using your preferences:<br> <br> <font color="<%= request.getParameter("fontColor")%>" size="<%= request.getParameter("fontSize") %>"> <%= request.getParameter("message")%> </font> </BODY>

Sending Output (Three Ways)


1. Type static messages directly in html mixing html and jsp html is known as template data 2. Use expressions <%= Your message goes here %> can create dynamic content this way <%= new java.util.Date() => 3. Use scriplets <% out.println(Your message goes here); %> you can put many output statements within a single scriplet however, you must use out object to display!

61

6/2/2012

<HTML> <HEAD> <TITLE>JSP output example 2</TITLE> </HEAD> <BODY> Your message is displayed using your preferred font format as follows:<br><br> <% out.println("<hr size=2 color=red>"); out.print("<font size= "); out.print(request.getParameter("fontSize")); out.print(" color= "); out.print(request.getParameter("fontColor")); out.println(">"); out.println(request.getParameter("message")); out.println("</font>" ); out.println("<hr size=2 color=red>"); %> </BODY> </HTML>

Sending Output Example

Storing Form Information


Use request object to get form info JSP uses variables to store the collected form values All variables must be declared before you can use them Date_Type variable_Name Data types are valid Java types Variables names are valid Java identifiers series of characters, digits, and underscores cannot begin with a digit by convention, use lowercase for first letter, capitalize beginning of each word case sensitive!

62

6/2/2012

Storing Form Information

<% // Retrieve form info and store in String // variable String major = request.getParameter(major); // // later display using out object out.println("Your major is " + major); %> <!- alternatively use expression --> Your major is <%= major %>

Using Basic JSP Techniques

63

6/2/2012

Scripting With JSP Elements

Page Directives
Page directive attributes apply to the entire JSP page: <%@ page attribute1=value1 attribute3= %> OR <%@ page attribute1=value1 %> <%@ page attribute2=value2 %> attribute2=value2

64

6/2/2012

Import Attribute
Make Java classes available to the scripting environment Use Java API to add power to your JSP script Reference class without specifying package names
<%@ page import=java.util.*,java.sql.* %>

Using java.util.Date class


Without import:
<% java.util.Date today = new java.util.Date();%>

If the class imported, then:


<% Date today = new Date(); %>

65

6/2/2012

Session Attribute
HTTP is stateless
JSP provides session management

Session attribute specifies whether session should be created


Then, can hold information across multiple requests Default value is true If the value is set to false, then no session is created

Session Attribute
A session begins when a user requests a JSP page the first time Session can be destroyed many different ways
User closes web browser Server terminates due to inactivity You can terminate session in code

66

6/2/2012

Session Object Example


<%@ page import="java.util.*" session="true" %> <HTML> <HEAD> <TITLE>Session attribute</TITLE> </HEAD> <BODY> Is this a new session? <%= session.isNew() %><br> Current time: <%= new Date() %> <br> <% Date date = new Date(session.getCreationTime()); %> The session created on :<%= date %><br> </BODY> </HTML>

Session Object Example


<%@ page import="java.util.*" session="false" %> <HTML> <HEAD> <TITLE>Session attribute</TITLE> </HEAD> <BODY> <% HttpSession mySession = request.getSession(true); %> Is this a new session? <%= mySession.isNew() %><br> Current time: <%= new Date() %> <br> <% Date date = new Date(mySession.getCreationTime()); %> The session created on :<%= date %><br> </BODY> </HTML>

67

6/2/2012

Buffer Attribute
Specifies the size of the buffer used by the implicit out variable
<%@ page buffer=sizekb %> <%@ page buffer=none %>

If a buffer is specified then output is buffered with a buffer size not less than the specified size

Server may still increase buffer size

Buffer Attribute Example


<HTML> <HEAD> <TITLE>Buffer attribute</TITLE> </HEAD> <BODY> <%@ page buffer="16kb" %> The buffer attribute is set to "16kb"<br> <hr align=left width=250 color=red> Let's send some text to the HTML output stream<br> The content is buffered. <% out.clear(); %> The buffered content is cleared from the buffer.<br> </BODY> </HTML>

68

6/2/2012

Buffer Attribute Example


<HTML> <HEAD> <TITLE>Buffer attribute</TITLE> </HEAD> <BODY> <%@ page buffer="none" %> The buffer attribute is set to "none".<br> <hr align=left width=250 color=red> Let's send some text to the HTML output stream.<br> The content is not buffered. <% try{ out.clear(); } catch (Exception e){} %> The buffered content is not cleared.<br> </BODY> </HTML>

isThreadSafe Attribute
Specify whether to allow more than one thread to execute the JSP code

<%@ page isThreadSafe=true %> <%@ page isThreadSafe=false %>

69

6/2/2012

Include Files
Add content from another file to your page Could be static content

navigation links headers and footers


Could be dynamic content

reusable JSP code

Include Directive
Format
<%@ include file=relative URL %>

Alternative format (xml) <jsp:directive.include file=relative URL /> Included content is merged into page at translation time!

This is called a static include Can result in inconsistencies when included file is updated Updates are not reflected in already translated pages!

70

6/2/2012

Include Action
Form
<jsp:include page="Relative URL" flush="true" />

The action does not merge the actual contents of the specified page at translation time The page is included each time the JSP page is requested
Updates are always reflected

This is an action, not a directive Performance cost to do this flush set to true to force current page buffer to be flushed before new file is included

Variable Duration

The duration of variable (also called its lifetime) is the period during which the variable exists in memory Variables of instance duration exist throughout the lifetime that a servlet is loaded in memory Variables of local duration exist only during processing of single page

71

6/2/2012

Variable Duration Example


<HTML> <HEAD><TITLE>Variable duration</TITLE></HEAD> <BODY> <%! int count1 = 0; %> <% int count2 = 0; %> <% count1++; count2++; %> Use the counter variable declared in JSP declaration<br> <b>This page has been accessed <font size=6 color=red><%= count1 %> </font> <% if(count1 == 1) { %> time. <% }else{ %> times. <% } %> </b><br><br>

Variable Duration Example


Use the counter variable declared in JSP sriptlet<br> <b>This page has been accessed <font size=6 color=red><%= count2 %> </font> <% if(count2 == 1) { %> time. <% }else{ %> times. <% } %> </b><br><br> <a href="example10.jsp">Reload this page</a> </BODY> </HTML>

72

6/2/2012

Implicit Objects

Implicit Objects
Objects created by the servlet container application session request response exception out Config pageContext page

73

6/2/2012

application implicit object

The JSP implicit application object is an instance of a java class that implements the javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and set information about the web application in which it is running.

application object example


One.jsp <html> <body> <% application.setAttribute(variable1,value1); %> </body> </html> Two.jsp <html> <body> <% =application.getAttribute(variable1,value1) %> </body> </html>

74

6/2/2012

session implicit object

The JSP implicit session object is an instance of a java class that implements the javax.servlet.http.HttpSession interface. It represents a client specific conversation.

The session implicit object is used to store session state for a single user.

One.jsp <html> <body> <% session.setAttribute(variable1,value1); RequestDispatcher rd=request.getRequestDispatcher(two.jsp); rd.forward(request,response); %> </body> </html> two.jsp <html> <body> <% =session.getAttribute(variable1) %> </body> </html>

75

6/2/2012

response implicit object

The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.

response implicit object


One.jsp <html> <body> <% response.setContentType(text/html); response.sendRedirect(two.jsp); %> </body> </html>

76

6/2/2012

request implicit object


The JSP implicit request object is an instance of a java class that implements the javax.servlet.http.HttpServletRequest interface. It represents the request made by the client. The request implicit object is generally used to get

request implicit object

The JSP implicit request object is an instance of a java class that implements the javax.servlet.http.HttpServletRequest interface. It represents the request made by the client.

The request implicit object is generally used to get request parameters, request attributes, header information and query string values.

request implicit object Login.html <html> <body> <form method=get action=LoginValidation.jsp> UserName: <input type=text name=userName /> Password: <input type=password name=password/> <input type=submit value=login/> </form> </body> </html>

77

6/2/2012

request implicit object


LoginValidation.jsp

<html> <body> <%=request.getParameter(UserName) %> <%=request.getParameter(Password) %> </body> </html>

out implicit object


The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class. It represents the output content to be sent to the client. The out implicit object is used to write the output content.

78

6/2/2012

out implicit object


Login.html <html> <body> <form method=get action=LoginValidation.jsp> UserName: <input type=text name=userName /> Password: <input type=password name=password/> <input type=submit value=login/> </form> </body> </html>

out implicit object


LoginValidation.jsp

<html> <body> <% out.println(request.getParameter(UserName)); out.println(request.getParameter(Password); %> </body> </html>

79

6/2/2012

exception implicit object

The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occured exception that caused the control to pass to the JSP error page.

config implicit object

The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.

80

6/2/2012

config implicit object

<html> <body> <%=config.getServletName() %> </body> </html>

page implicit object


The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP page. That is, it serves as a reference to the java servlet object that implements the JSP page on which it is accessed. It is not advisable to use this page implict object often as it consumes large memory.

81

6/2/2012

pageContext implicit object

The JSP implicit pageContext object is an instance of the javax.servlet.jsp.PageContext abstract class. It provides useful context information. That is it provides methods to get and set attributes in different scopes and for transfering requests to other resources. Also it contains the reference to to implicit objects.

Scopes of Jsp objects


The availability of a JSP object for use from a particular place of the application is defined as the scope of that JSP object. Every object created in a JSP page will have a scope. Object scope in JSP is segregated into four parts and they are page request session application.

82

6/2/2012

Page Scope
page scope means, the JSP object can be accessed only from within the same page where it was created. The default scope for JSP objects created using <jsp:useBean> tag is page.

JSP implicit objects out, exception, response, pageContext, config and page have page scope.

Request Scope

A JSP object created using the request scope can be accessed from any pages that serves that request. More than one page can serve a single request. The JSP object will be bound to the request object. Implicit object request has the request scope.

83

6/2/2012

Session Scope

session scope means, the JSP object is accessible from pages that belong to the same session from where it was created. The JSP object that is created using the session scope is bound to the session object. Implicit object session has the session scope.

Application scope

A JSP object created using the application scope can be accessed from any pages across the application. The JSP object is bound to the application object. Implicit object application has the application scope.

84

6/2/2012

JSP Standard actions JSP Standard action are predefined tags which perform some action based on information that is required at the exact time the JSP page is requested by a browser.

for instance, access parameters sent with the request to do a database lookup The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.

JSP Standard actions


Action element <jsp:useBean>s <jsp:getProperty> <jsp:setProperty> <jsp:include> Description Makes a JavaBeans component available in a page Gets a property value from a JavaBeans component and adds it to the response Sets a JavaBeans component property value Includes the response from a servlet or JSP page during the request processing phase Forwards the processing of a request to servlet or JSP page Adds a parameter value to a request handed off to another servlet or JSP page using <jsp:include> or <jsp:forward> Generates HTML that contains the appropriate browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software

<jsp:forward>

<jsp:param>

<jsp:plugin>

85

6/2/2012

The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or a dynamic resource in a JSP file. The results of including static and dynamic resources are quite different. If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page. The syntax for the jsp:include element is:

86

Vous aimerez peut-être aussi