Servlets Servlets are modules that extend the functionality

  • Slides: 24
Download presentation
Servlets • Servlets are modules that extend the functionality of a “java -enabled” web-server

Servlets • Servlets are modules that extend the functionality of a “java -enabled” web-server • They normally generate HTML code and web content dynamically. This is sent to the browser which displays it. • For example, they send a query to a databased on parameters sent by the browser and send the results to the browser in html format

Preliminary work • The package javax. servlet provides the interfaces and classes which allows

Preliminary work • The package javax. servlet provides the interfaces and classes which allows the compilation and execution of servlets • It does not come with the standard distribution of j 2 sdk, it is necessary to download the jar file containing it and make it „visible“ when compiling the programs • for executing servlets normally the java-enabled server will provide the necessary classes • Every server follows different rules for the way servlets should be deployed (make them available for clients) • Normally, they should be copied in a certain directory For example, in tomcat servlets under <tomcatroot>webappsexamplesWEB-INFclasses can be contacted by the url http: //host: port/servlet/examples/servletname • Sometimes there is also necessary to have a manifest file (in XML) for defining aliases and parameters

Anatomy of a Servlet • A new servlet can be written by extending the

Anatomy of a Servlet • A new servlet can be written by extending the class Http. Servlet which has the following pre-defined methods – init() is called when the servlet is “uploaded” the first time (this can vary depending on the server) – do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException Is called every time the servlet is contacted by a GET request (which is the default way) do. Post(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException Is called when the client contacted the servlet with a POST request

Anatomy of a Servlet (2) • A web browser generates a GET request when

Anatomy of a Servlet (2) • A web browser generates a GET request when it sends an http request from the user • For example, by entering http: //www. yahoo. com in the browser it will send the string „GET index. html Httpx. x“ • When a servlet is contacted the first time it starts 4 -6 threads are initialised to serve future clients (why ? ) • It is very often to see servlets contacted by a POST request generated by an HTML „form“ which also passes a lot of parameters

The Http. Servlet. Request Parameter • Http. Servlet. Request is the class of one

The Http. Servlet. Request Parameter • Http. Servlet. Request is the class of one of the two parameters the server calls do. Get and do. Post and implements the interface Servlet. Request which give access to: – Information about the client, for example, parameters passed, protocol used, client’s host, etc. – The input stream, Servlet. Input. Stream is used by the servlet to receive data from the client when the method POST or PUT has been used.

The Http. Servlet. Response parameter • Http. Servlet. Response is the class of the

The Http. Servlet. Response parameter • Http. Servlet. Response is the class of the second argument. • Implements the interface Servlet. Response which provides methods for : – Declaring the MIME type of the answer that will be sent to the client – The output stream Servlet. Output. Stream and a Writer through which the servlet can send dinamically generated html code.

A first Example • Writing a servlet with Netbeans is very easy • Also

A first Example • Writing a servlet with Netbeans is very easy • Also the deplyment is done automatically – Open netbeans – Create a web project (this will create a lot of directories for putting the different kind of files) – Create a servlet – Copy the code of Simple. Servlet. java – Run the file

Simple. Servlet • Simple. Servlet extends Http. Servlet which implements the interface Servlet. •

Simple. Servlet • Simple. Servlet extends Http. Servlet which implements the interface Servlet. • Overwrites the method do. Get from the Http. Servlet class. do. Get is called by the service method • Inside the method do. Get, – The client´s request is represented by the object of the class Http. Servlet. Request. – The answer by an object of the class Http. Servlet. Response – Because the answer to the client is text, the servlet creates an object from the class Writer from the parameter Http. Servlet. Response.

A second example • Implementing a web counter • It will count – how

A second example • Implementing a web counter • It will count – how many times it has been created (init) – how many times all instances has been called – Haw many times the instance that has been contacted has been already called • See Count. java

Using initialization parameters (also called context parameters) • In all servers there is the

Using initialization parameters (also called context parameters) • In all servers there is the possibility to use a configuration file for servlets called web. xml • It can be edited “by hand” with a text editor • In this file some parameters for the servlet can be defined • Allows servlet to change functionality of servlet without compiling them again • In netbeans the parameters are defined while creation and may be modified afterwards browsing the file project. Name/build/web/WEB-INF/web. xml • See Show. Parameters. java

Parameters passed by client • The client can pass parameters with the request according

Parameters passed by client • The client can pass parameters with the request according to the following format – http: //host: port/servlet? param 1=value 1&param 2=value 2 • The servlet can ask for those values in the following way: – String value = req. get. Parameter(param 1); – String[] value = req. get. Parameter. Values(param 1) • Parameter names and values are strings • see Show. Parameters 1. java and call with – http: //host: port/Servlet. Parameter 1? name=nelson

The normal way is to gather parameters with forms • A Form is an

The normal way is to gather parameters with forms • A Form is an HTML page which may contain graphical objects to gather information which ist sent to the server in an URL • We can use the same servlet but call it whith !!!! - Show. Parameters 1. html (add to project an html file) • Example 1: – Show. Parameters. Request. java called by Show. Parameters. Post. Form. html • Example 2: – Survey. Servlet. java called by Jdc. Survey. html

Session Tracking • Session tracking is a mechanism that servlets may use to maintain

Session Tracking • Session tracking is a mechanism that servlets may use to maintain a state for a client during a session • A session is a dialogue between an instance of a browser and the server for a certain period of time (default is 30 minutes). • It is possible to associate information to the session objects, which is kept on the server during the session • The session is not managed by the programmer but by the server. • See Session. Servlet

Some methods • Http. Session sesion = request. get. Session(true) cretes a session object

Some methods • Http. Session sesion = request. get. Session(true) cretes a session object if it did not existed already • sesion. is. New()returns true if the above methods created a new object • sesion. put. Attribute/Value(String nombre, Object valor) associates to the parameter nombre the value valor (value se usa hasta v 2. 2) • Object o = sesion. get. Attribute/Value(“nombre”)returns the object associated to that prameter for that session • sesion. remove. Attribute/Value(“nombre”)deletes the object associated to the parameter named “nombre” for that session • Enumeration[]valores = sesion. get. Attribute. Names() • String[]valores = sesion. Value. Names() returns an array/ennumeration of names for attributes/values the session has stored • long l = sesion. get. Creation. Time()returns the time (in milliseconds starting from 1. 1. 70 0: 0: 0 ) the session object was created • Long l = sesion. last. Accessed. Time() returns the time of the las access • sesion. set. Max. Inactive. Interval(int seconds)sets the timeout of the session

Using Cookies • Cookies are another way to keep track of what the client

Using Cookies • Cookies are another way to keep track of what the client has been doing • Trough a cookie the servlet can send information to the client so it can store it and send it every time it contacts the server again. • The Servlets send cookies to the clients adding information to the header of the Http response it send to the client. • The clients automatically return these cookies when thy contact the server again for a further request as additional information on the HTTP request. • Cookies have a name and a value (both strings) Additionally they can store a comment • A server can pass more than a cookie to the client.

Using Cookies • To send a cookie 1. Instantiate a Cookie object 2. Set

Using Cookies • To send a cookie 1. Instantiate a Cookie object 2. Set attributes (pair name-value) 3. Send cookie • To retrieve the information of a cookie, 1. Retrieve all cookies from the client 2. Find the cookie you need by its name 3. Retrieve the associated value

Examples of Cookies • The first example (Cookies. java) shows the times when the

Examples of Cookies • The first example (Cookies. java) shows the times when the client contacted the servlet for the first time (via do. Get method) and the time when it contacted the server by pressing the button • The second example (Cookie. Example) shows how to retrieve all the cookies • The third example (Set. Cookie and Show. Cookies) shows how to put time-out values for a cookie

¿ Cookies or Sessions ? • With sessions the information is stored on the

¿ Cookies or Sessions ? • With sessions the information is stored on the server, this means, there is a state which has to be administrated carefully • With cookies it is the client which has the information, this means the information travels back and forth every time the client contacts the server • The client can prohibit the use of cookies

The headers of request and response • Provide high level information from the client

The headers of request and response • Provide high level information from the client and to the client – The request allows the servlet to obtain interesting characteristics of the client – The response allows the servlet to define how the information will be delivered to the browser • In general, they help make the dialog with the client more effective • For the request, there are methods called get. XXX or get. Header(xxx) to obtain information • For the response, there are methods called set. Header(xxx) or set. XXX for defining the form of the response data. • Often both are required to be used in combination to generate an adequate response

Some get for the request • get. Cookies(): received the cookies which the client

Some get for the request • get. Cookies(): received the cookies which the client browser may have sent • get. Auth. Type(): is used for clients trying to access a page for which a password is required • get. Remote. Host(): to obtain the hostname of the client • get. Method(): to get the name of the method with which the browser contacted the servlet (GET, POST, etc. . ) • get. Protocol(): version of the HTTP protocol the client is using • get. Header. Names(): the name of all the headers the client has sent (is variable depending on the HTTP and browser version

Some xxx for the get. Header(xxx) • • • Accept: which MIME types the

Some xxx for the get. Header(xxx) • • • Accept: which MIME types the client “understands” Accept-Charset: which character set the client is using Accept-Encoding: encoding algorithms the client accepts Accept-Language: language (en-us, sp, ge, . . ) Authorization: to identify clients with a protected page Host: the client’s computer name Referer: the URL of the page that generated the contact Cookie: to obtain the cookies Connection: if the client can manage persistent connections (for example, in order to send files)

Some set for the response • set. Content. Type(xxx): for informing the MIME type

Some set for the response • set. Content. Type(xxx): for informing the MIME type of the response • set. Content. Length(xxx): for informing the length of the response (used when transmitting bytes) • add. Cookie(): to add cookies with information to the client • send. Redirect(): to redirect the request to another URL • set. Header(xxx, xxx) a general form • set. Int. Header(xxx, xxx) when the second argument is an integer (no need to convert to string)

Some xxx for the set. Header(xxx, xxx) • • • Content-Type: some MIME type

Some xxx for the set. Header(xxx, xxx) • • • Content-Type: some MIME type like “image/gif” Content-Length: length (para bytes) Content-Encoding: codification Content-Language: language Cache: como se debe manejar el cache en el cliente (ej, nocache, no-store, must-revalidate, max-age=xxxx, • Refresh: informs the browser how often the page should be refreshed • www-Authenticate: for managing pages protected with passwords

Some more elaborated exemples showing the use of these methods • Show. Request. Headers:

Some more elaborated exemples showing the use of these methods • Show. Request. Headers: just shows the headers of the request • Protected. Page: shows how to ask for a password (run Password. Builder first) • Ping & Pong: shows redirection