You are on page 1of 92

Y  




2  
2

2
r 
 

 
‡ 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
r 
 

 
‡ For HTTP default port is 80
‡ The Web Server will be listening in that Server 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
r 
 

 


    


  


  


 
   
  

 
   
 


   

|
 
  
r 
‡ This kind of Client/Server communication
should follow a Protocol for its smooth
functioning
‡ Hyper Text Transfer Protocol or HTTP is the
protocol used by the Web
‡ According to the HTTP protocol, the client
should send a Request to the server in a special
format
‡ Based on the Request, the server will send back a
Response, which again is in a special format
r 


‡ The following is the request generated by an
Internet Browser when the URL was
http://www.yahoo.com

GET http://www.yahoo.com/ HTTP/1.0


Accept: image/gif, image/x-xbitmap, image/jpeg,image/pjpeg,
application/vnd.ms-excel,application/vnd.ms-powerpoint,
application/msword, application/x-shockwave-flash, */*
Accept-Language: en-us
Cookie: B=frhg66l0d2t8v&b=2; CP=v=50312&br=i; CRZY1=t=1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
Host: www.yahoo.com
Proxy-Connection: Keep-Alive
r 


‡ The first thing specified by a Request is a HTTP
command called METHOD
‡ This tells the Server the kind of service you
require
‡ The two important methods are GET and POST
‡ This will be followed by the path of the
document the browser requires and the version
of HTTP used by the client
r 


‡ After this, the client can send optional header
information to tell extra things to the server
‡ The software used by the client, the content types
the client would understand etc are communicated
to the server with the help of these headers
‡ The headers will help the server to give the response
properly
‡ After the header information, the client should send
a blank line to indicate that the header information
is over
r 
 

‡ The server processes the request and sends a


Response
‡ The following is an example of a response
HTTP/1.1 200 OK
Date: Sat, 18 Mar 2000 20:35:35 GMT
Server: Apache/1.3.9 (Unix)
Last-Modified: Wed, 20 May 1998 14:59:42 GMT
Content-Length: 2000
Content-Type: text/html

<HTML><HEAD> </HEAD> <BODY>


«
</BODY> </HTML>
r 
 

‡ The first line of the Response is called the status


line
‡ The status line should contain the HTTP version,
Status Code and a Status Description
‡ The following are some examples of status code
used by HTTP
Ł 200 - Ok
Ł 400 ± Bad Request
Ł 401 ± Unauthorized
Ł 403 ± Forbidden
Ł 404 ± Not Found
Ł 500 ± Internal Server Error
r 
 

‡ After the status line comes the Response headers


‡ The software used by the server, content type of
the response etc will be communicated to the
browser using these headers
‡ There should be a blank line to show that the
header information is over
‡ After the headers, the server sends the data on
success or an error description on failure
Î 

‡ From the web, we get static pages as well as
dynamic pages
‡ Static page is a page that does not change with
user and/or time
‡ Dynamic page is a page that changes with user
and/or time
‡ For delivering a static page, all we require at the
server side is the Web Server and the HTML file
Î 

‡ But a dynamic page cannot be created in
advance and kept as an HTML file
‡ So, to have a dynamic page, apart from the Web
Server, we require a program to generate the
dynamic content
‡ In some cases, the Web Server itself will be able
to execute this program
‡ In some other cases, we may require an extra
software component that can execute this
program
Î 
 Web Server

1. User Submits Form and resultant URL: abcbooks.co.in


http://abcbooks.co.in/eshop/ 202.68.33.49
PurchaseItem?iname=Floppy+Disc&qty=12

2. Send HTTP Request


for eshop/PurchaseItem with 3. Forwards the
= 


params request to
·nline Shopping a Server Side
Item Floppy Disc Program for
Name
12 The Internet execution
Quantity
Submit

4. Compose HTML
output

5. Send HTTP Response


= 

 which contains the HTML output
of the request
·nline Shopping
Bill
Floppy Disc Server Side Program
Price: Rs. 240/-

Goods once sold will not be taken back


Happy Shopping
 
 Y 

Y
‡ CGI technology was first used to generate
dynamic content
‡ CGI enables web server to call an external
program and pass HTTP request information to
that external program to process the request
‡ The response from external program is then
passed back to the web server which forwards it
to the client browser.
‡ CGI program can be written in any language
which can be called by web server.
‡ Perl was popular language for CGI programs
Î Y
‡ In CGI, the server should start a new process to
run a CGI program for each client request
‡ This (process creation) requires significant time
and resources (CPU cycles and memory)
‡ So, CGI programs were not scalable (As number
of users increases, it fails)
‡ CGI with PERL also launches a separate
interpreter for each request.




 
 
‡ Servlet was introduced by Sun Microsystems in
1996 as an effective alternative for CGI programs
‡ Servlet is a Java program that is executed at the
server
‡ The output of the Servlet can be HTML
‡ Thus, Servlets can be used to generate dynamic
pages


 

‡ For executing the Servlets, the Web Server requires
the help of another piece of software called the
Servlet Container
‡ The terms Application Server, Servlet Engine and
Servlet Runner are also used instead of Container
‡ The Servlet Container may be built into the Web
Server or can be implemented as a separate module
‡ Tomcat is a Servlet Container that is popularly used
j  



Ł They are persistent, their life cycle extends beyond
the HTTP request.
(Servlet waits in memory for client requests, it is not
unloaded from the memory after serving client
request)

Ł They exist in a separate memory space.


Ł Process is created only once when first time servlet
is called. Then for each client request, a thread is
created (and not new process) which takes memory
of the same Process Control Block. This saves
memory resources and CPU time.

Ł They are flexible as they use standardized API.


j  



‡ Performance of servlets is superior to CGI
‡ Servlet applications are portable to other operating
systems
‡ Servlets have access to the rich java library, which
helps speed up the development process
‡ Servlets are managed by JVM, you need not worry
about memory leak or garbage collection, hence
applications are robust
‡ Since java is widely accepted technology, you can
easily find and purchase components that suit your
needs, which saves development time



‡ The Container should be able to execute any
Servlet
‡ This requirement calls for a standard interface
for all the Servlets
‡ A class should implement the interface called
Servlet in the package javax.servlet to become a
Servlet
 


   
    

   



 

 

  




 

  
     

Y 
  

    

 
 
  

 
        
 
 



‡ Client opens a connection to the server
‡ Client makes a request to the server:
Ł GET /index.html HTTP/1.0
‡ The Server responds to the request
Ł HTTP/1.0 200 OK
Ł [more header stuff]
Ł CRLF
Ł <HTML>
Ł [html code from index.html]
Ł </HTML>
‡ The connection is closed by the server (or client)
 
r 
‡ Simplest and Most frequently used method

‡ Used to request a read only resource from the server,


such as a static HTML page

‡ Can be used to retrieve dynamic information by


including query parameters in the request URL

‡ Parameters are stored in the URL itself:


Ł GET /index.htmlu  
  
HTTP/1.0
 
r 
‡ GET method is used to send document,results
from a database query etc.

‡ The information is appended to URL.

‡ The total length of characters in GET method is


confined to 240 characters only by some servers.
 
r 
‡ Allows the user to pass information to the
server.

‡ All parameter information is stored in the body


of the request rather than in the URL, which
provides for more privacy

‡ No set limit on the amount of information that


can be passed as there is with the parameter
passing of a GET
 
r 
‡ A POST is typically generated by the browser in
response to a click on a Submit button on an
HTML form that declares the POST method
Ł POST /login.html HTTP/1.1
Ł User-Agent: Mozilla/4.50 [en] (WinNT; I)
Ł Accept: image/gif, image/jpeg
Ł Content-Length: 34
Ł CRLF
Ł user=mark&password=secret
 
r 
‡ POST method is used for sending credit card no.,
updated database etc.
‡ The information is passed as the part of its
HTTP request body.
‡ The information exchange is invisible to the
client.
‡ Unlike GET method, the information length is
unlimited.

r 

‡ r  - Identical to GET except that it only retrieves
the header, not the body.
‡  - a 1.1 method for file uploads
‡    - a 1.1 method for deleting resources on the
server (with permission)
‡ 
- a 1.1 method for requesting information
regarding the communication options that the server
supports
‡   - a 1.1 method that returns the same request
back to the client, usually for debugging purposes.











‡      
Ł Specifies how to develop applications
‡ 
Ł Includes support for applicable network services, and
a runtime for executing the application
‡ 

Ł Deployment is the process of installing the application
on the server.
Ł Process also includes configuring application
components such as specifying initialization
parameters and specifying any databases




  

‡ CGI
‡ NS API
‡ ASP
‡ Servlets
‡ JSP




 
!  #  
 
  
 
 ! "
     

$%%" 

  
       
  
$%%"   



  &       

G  

$   


"
 

 
÷ 

 
÷ ÷
 

‡ Servlet is loaded and initialized


‡ It handles the client requests
‡ It is unloaded


 "
 

‡   !
Ł Called by server at loading of the servlet
Ł Called before the servlet handles it¶s first
request
Ł Accepts a ServletConfig object that
contains the initialization parameters,
configuration values stated in web.xml
Ł It can throw ServletException
Ł If overridden, must call super.init(config)
first
Ł e.g. A counter for servlet calls


 "
 
 
‡ "#  !
Ł Serving the client requests
Ł Delegation of requests to appropriate methods
Ł Takes two arguments as objects of :
ServletRequest (contains client request) ,
ServletResponse (contains servlet¶s response)
- Can throw ServletException, IOException
‡  
Ł is called at servlet unloading. This normally
happens when servlet container is shut down or the
servlet container needs some free memory
Ł Free the resources and do cleanup tasks
Ł Is called only after all threads within the servlet¶s
service method have exited or after timeout
Ł Make state persistent

Y  

‡ #
"
Ł From package javax.servlet
Ł Provides basic implementation of the Servlet
interface
Ł Abstract class, and all subclasses should implement
the service() method

‡ r
"!
Ł From package javax.servlet.http
Ł Provides an HTTP specific implementation of the
Servlet interface
Ł This will most likely be the class that all of our
servlets will extend

r

 
‡ protected void "#(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, java.io.IOException

‡ protected void  (HttpServletRequest req,


HttpServletResponse resp) throws
ServletException, java.io.IOException

‡ protected void  (HttpServletRequest req,


HttpServletResponse resp) throws
ServletException, java.io.IOException
 # 

  r




‡       
         
! "  #  "
$%%

‡ 2 
‡    !V    ! "
Ł    & &  
    !'
Ł &       &
 &  "% "   '
Ł   "      
 # 

  r




‡   ( "   V  
 
Ł     "   &  
"    '
Ł &    % "
   " "   '

‡     ' !' ! V 2  


Ł    "&") 
)   ) " %&* " %
$(%+%,
 # 

  r




‡ public String $
()
Ł Returns the query string that is contained in the
request URL after the path.
Ł This method returns null if the URL does not have a
query string.

‡ public String (String name)


Ł Returns the value of a request parameter as a String,
or null if the parameter does not exist.
Ł Request parameters are extra information sent with
the request.
Ł For HTTP Servlets, parameters are contained in the
query string or posted form data
! # 

  r





‡ public HttpSession 


(boolean create)
Ł Returns the current HttpSession associated with
this request or, 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.

 

$
‡ Write a Servlet to print ³Hello´ message on
browser
Ł Step 1- Write A HelloServlet class
Ł Step 2- Make an entry in web.xml
Ł Step 3- Give the request to the
HelloServlet

% 
r



import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException

{ response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<html><body><head><title>Hello
World!</title></head><body><h1>Hello
World!</h1></body></html>");
}
}

&
 # 



<web-app>
<servlet>
<servlet-name>=</servlet-name>
<servlet-class>#%&r
"</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>=</servlet-name>
<url-pattern>=</url-pattern>
</servlet-mapping>
</web-app>

'(







    )"

URL: http:// ip address of server : port


number/hello




Y 


‡ The ServletRequest interface contains various


method to handle client request to access a
servlet.
‡ Whenever a servlet is invoked ,the web container
passes the objects that implements
ServletRequest and and ServletResponse to the
service() method of the servlet.






‡ public String getParameter (String paramname)
‡ public String getParameterValues(String
paramName)
‡ public Enumeration getParameterNames()
‡ public String getRemoteHost()
‡ public String getRemoteAddr()



 
Y 


‡ ServletResponse interface contains various


methods that enable a servlet to respond to the
client request.
ÈA servlet can send the response either as
character or binary data.
ÈThe PrintWriter stream can be used to send the
character data as servlet response,and
ServletOutputStream stream to send binary data
as servlet response




 
Y 


‡ public ServletOutputStream getOutputStream()


throws IOException
‡ public PrintWriter getWriter() throws
IOException
‡ public void setContenetType(String Type)


 
#Y 


‡ The ServeletContext interface proides


information to servlet regarding the
environment in which they are running.
‡ The context is also called as servlet context or
web context and is created by the web container
as an object of the servletContext interface.
‡ This object represents a context within which a
web application executes.



 
#Y 


‡ public void setAttribute(String,Object )


‡ public Object getAttribute(String attrname)
‡ public Enumeration getAttributeNames()
‡ public String getInitParameter(String pname)
‡ public Enumeration getInitParameterNames()
‡ public int getMajorVersion()
‡ public int getMinorVersion()

r

 
‡ protected void "#(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, java.io.IOException

‡ protected void  (HttpServletRequest req,


HttpServletResponse resp) throws
ServletException, java.io.IOException

‡ protected void  (HttpServletRequest req,


HttpServletResponse resp) throws
ServletException, java.io.IOException
 # 

  r






‡      


        
! "  # "
$%%

‡ 2 
‡    !V    ! "
Ł    & &  
    !'
Ł &       &
 &  "% "   '
Ł   "      
 # 

  r





‡   ( "   V  
 
Ł     "   &  
"    '
Ł &    % "
   " "   '

‡     ' !' ! V 2  


Ł    "&") 
)   ) " %&* " %
$(%+%,
 # 

  r





‡ public String $
()
Ł Returns the query string that is contained in the
request URL after the path.
Ł This method returns null if the URL does not have a
query string.

‡ public String (String name)


Ł Returns the value of a request parameter as a String,
or null if the parameter does not exist.
Ł Request parameters are extra information sent with
the request.
Ł For HTTP Servlets, parameters are contained in the
query string or posted form data
! # 

  r





‡ public HttpSession 
(boolean create)
Ł Returns the current HttpSession associated with
this request or, 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.

r


 
Y 


‡ The HtpServletResponse interface extends the


ServletResponse interface and provides methods
to handel response ,status code and response
headers for servlets that communicates using
HTTP.


r
 
Y 


‡ void setHeader(String hname,String hvalues)


‡ void setIntHeader(String hname,long datev)
‡ void setDateHeader(String hname, long datev)
‡ void sendRedirect(String url)
j
 Y 


Step 1:
Make an entry of <init-param>in a web.xml file
Step 2:
Write a Servlet which will read this information
from web.xml

 # 



<web-app>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>myPack.HelloServlet</servlet-class>
<init-param>
<param-name>user</param-name>
<param-value>scott</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
</web-app>



 



 #
‡ ServletConfig is used to retrieve initialization
information

public void doPost(HttpServletRequest req,


HttpServletResponse res) throws
ServletException,IOException
{
// this method is from ServletConfig
String user=("user");
}


 
#
‡ It provides access to resources and facilities common to
all servlets in the application

‡ Specific to a particular web application running in a JVM

‡ Each application will have a single servlet context


associated with it

‡ Two ways to put context information using


Ł web.xml file
Ł ServletContext


 



‡ ServletConfig has a method getServletContext ()
Which is used to retrieve ServletContext
//code in service() method
ServletContext ctx=getServletContext();
String user = ctx.getInitParameter(³user´);
String password = ctx.getInitParameter(³password´);

‡ To set the context parameters using ServletContext


ctx.setAttribute(³driver´,´drivername´);

‡ To get the context parameters


String driver=(String)ctx.getAttribute(³driver´);
ë 

‡ Servlet interface
Ł Implemented by all servlets
Ł Many methods invoked automatically by server
£ Similar to applets (paint, init, start, etc.)
Ł abstract classes that implement Servlet
£ GenericServlet (javax.servlet)
£ HTTPServlet (javax.servlet.http)
‡ Methods
Ł void init( ServletConfig config )
£ Automatically called, argument provided
ë 
 
‡ Methods
Ł ServletConfig getServletConfig()
£ Returns reference to object, gives access to config info
Ł void service ( ServletRequest request,
ServletResponse response )
£ Key method in all servlets
£ Provide access to input and output streams
£ Read from and send to client
Ł void destroy()
£ Cleanup method, called when servlet exiting
HttpServlet 
‡ HttpServlet
Ł Base class for web-based servlets
Ł Overrides method service
£ Request methods:
£ GET - retrieve HTML documents or image
£ POST - send server data from HTML form
Ł Methods doGet and doPost respond to GET and
POST
£ Called by service
£ Receive HttpServletRequest and HttpServletResponse
(return void) objects
r

‡ HttpServletRequest interface
Ł Object passed to doGet and doPost
Ł Extends ServletRequest
‡ Methods
Ł String getParameter( String name )
£ Returns value of parameter name (part of GET or POST)
Ł Enumeration getParameterNames()
£ Returns names of parameters (POST)
Ł String[] getParameterValues( String name
)
£ Returns array of strings containing values of a parameter
Ł Cookie[] getCookies()
£ Returns array of Cookie objects, can be used to identify client
r


‡ HttpServletResponse
Ł Object passed to doGet and doPost
Ł Extends ServletResponse
‡ Methods
Ł void addCookie( Cookie cookie )
£ Add Cookie to header of response to client
Ł ServletOutputStream getOutputStream()
£ Gets byte-based output stream, send binary data to client
Ł PrintWriter getWriter()
£ Gets character-based output stream, send text to client
Ł void setContentType( String type )
£ Specify MIME type of the response
£ Helps display data
  
 
‡ HTTP is a stateless protocol and therefore
cannot store the information about the user
activities across web pages.
‡ Session management is the process of keeping
track of the activities of a user across web pages.
‡ Session tracking can also be used to keep track
of the user¶s perferences.
ë
‡ Web sites
Ł Many have custom web pages functionality
£ Custom home pages - http://my.yahoo.com/
£ Shopping carts
£ Marketing
Ł HTTP protocol does not support persistent
information
£ Cannot distinguish clients
‡ Distinguishing clients
Ł Hidden variables
Ł Cookies
Ł Session Tracking

‡ Cookies
Ł Small files that store information on client's
computer
Ł Servlet can check previous cookies for information
‡ Header
Ł In every HTTP client-server interaction
Ł Contains information about request (GET or POST)
and cookies stored on client machine
Ł Response header includes cookies servers wants to
store
‡ Age
Ł Cookies have a lifespan
Ł Can set maximum age
£ Cookies can expire and are deleted
ë r
‡ HttpSession is an alternative to cookies. It
keeps the session data available until browsing
ends
‡ Methods
Ł getSession( createNew )
£ Class HttpServletRequest
£ Returns client's previous HttpSession object
Ł putvalue( name, value )
£ Adds a name/value pair to object
Ł getValueNames()
£ Returns array of Strings with names
Ł getValue( name )
£ Returns value of name as an Object
£ Cast to proper type
þ


   
‡ The server should be able to identify that a series
of requests are coming from the same client

‡ The application should be able to associate state


with each user¶s session

   

  

w   
  
w   
  

   
Different ways of Session Tracking:

‡ URLRewriting - encodeURL()

‡ Hidden Form Fields

‡ Cookies

‡ HttpSession
)"
 
‡ By rewriting URLs all links and redirections which are
created by a Servlet have to be encoded to include the
session ID.

‡ This is a less elegant solution (both, for Servlet


implementers and users) because the session cannot be
maintained by requesting a well-known URL or selecting
a URL which was created in a different (or no) session.

‡ It also does not allow the use of static pages. All HTML
pages which are sent within a session have to be created
dynamically.
)"
 
‡ The URL is constructed using an HTTP GET

‡ It may include a query string containing pairs of


parameters and values eg:
http://www.server.com/getPreferences?uid=usernam
e&bgcolor=red&fgcolor=blue.

‡ URLs can get quite lengthy.

‡ You have to be sure to append the information to every


URL that references your site.
)"
 
‡ Appending parameters brings up privacy
issues; you may not want the actual data you
are tracking to be visible.

‡ There's a loophole with this technique: users


can leave the session and come back using a
bookmark, in which case your session
information is lost.
r

 r "
‡ Hidden form fields store information about the
session. The hidden data can be retrieved later by
using the HTTPServletRequest object.

‡ Form fields can be used only on dynamically generated


pages, so their use is limited. And there are security
holes: people can view the HTML source to see the
stored data.

‡ <INPUT TYPE="HIDDEN" NAME="session"


VALUE="...">


‡ A Cookie is a string (in this case that string is the
 ) which is sent to a client to start a session.

‡ If the client wants to continue the session it sends back


the Cookie with subsequent requests. This is the most
common way to implement session tracking.

‡ Cookies store information about a session in a


human-readable file on the client's machine. The
server associates a session ID from the cookie with
the data from that session.


‡ A cookie cannot grow more than 4K in size, and no
domain can have more than 20 cookies.

‡ Cookies pose some privacy concerns for users.

Cookie c=new Cookie (³uid´,´joe´);


c.setMaxAge(60*60);
c.setDomain (³.myserver.com´);
c.setPath(³/´);
response.addCookie(c);

r
 !

‡ Obtain a session object

‡ Read or write to it

‡ Either terminate the session by expiring it, or do nothing so it will


expire on its own

‡ A session persists for a certain time period, up to forever, depending


on the value set in the servlet.

‡ A unique session ID is used to track multiple requests from the same


client to the server.


 r

‡  '
Ł Returns true if the client doesn't yet know about the session. If the
client has disabled cookies, then a session is new on each request.

‡ 
Ł Returns a string containing the unique identifier assigned to this
session. Useful when using URL rewriting to identify the session.

‡ (
Ł Binds an object to this session, using the name specified. (Note: this
replaces the putValue() method of JSDK 2.1.)


 
‡ In a web application scenario a servlet receives an HTTP
request from a client, processes application logic
partially and hands over the request to another servlet.

‡ The second servlet completes the application logic, and


either prepares the response, or requests a JSP page to
drive the response.

‡ There are two solutions to address the above


requirement:
Ł Servlet Chaining
Ł Request Dispatching


  
‡ This was a very widely used approach, and
supported by some of the servlet engine
vendors

‡ Not supported by the Java Servlet API


specification

‡ Instead use RequestDispatcher relies on servlet


container for chaining.


 
‡ This allows one servlet to dispatch the request to
another resource

RequestDispatcher
rd=getServletContext().getRequestDispatcher
(String path)
rd.forward(req,res)

!
‡ Should not write anything to the response.
‡ Use reset() method on response.
   
#


<web-app>
<servlet>«</servlet>
ü#)*
<param-name>user</param-name>
<param-value>scott</param-value>
ü #)*
ü#)*
<param-name>password</param-name>
<param-value>tiger</param-value>
ü #)*
</web-app>


*j


    

    
   
   
          
             
     
 
  
     

            


  
  

     


 
            

   

 !