Lecture9

advertisement
CS441
CURRENT TOPICS IN
PROGRAMMING LANGUAGES
Lecture 9
George Koutsogiannakis/ Summer 2011
1
Topics
• Continue with Servlets
–
–
–
–
–
–
–
Content Types
HTTP Tunneling.
URL connections.
Applet to Servlet communication.
Application to Servlet communication.
Session object.
Servlet to other server side resources
communication.
2
Servlets - Definition
• A servlet is a Java programming language class that is used to extend
the capabilities of servers that host applications accessed by means of a
request-response programming model.
• Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by web servers. For
such applications, Java Servlet technology defines HTTP-specific
servlet classes.
3
Servlets - Definition
• The javax.servlet and javax.servlet.http packages
provide interfaces and classes for writing servlets.
• All servlets must implement the Servlet interface, which
defines life-cycle methods.
• When implementing a generic service, you can use or
extend the GenericServlet class provided with the Java
Servlet API.
• The HttpServlet class provides methods, such as doGet and
doPost, for handling HTTP-specific services.
4
Servlet Engine and Servlets
• Communication from client is received by the web
server in the form of HTTP packets.
• The web server reads the packets and passes
information to the servlet engine (container).
• The container does the following:
5
Servlet Engine (container) and
Servlets
• Web Servers get the capability to communicate with
servlet programs installed in their environment by having
the servlet engine or container as part of their environment.
The container:
– Activates the init and getServletContext methods if
this is the first time that the servlet is being called after
the web server was activated.
– Calls the service method.
– The service method creates the request and response
objects.
6
Servlet Engine (container) and
Servlets
– The service method establishes the streams of
communication between the container and the servlet.
– The service method calls either the doPost or the
doGet method implementations in the servlet based on
the type of request that was recognized coming from
the client.
7
Servlet Context
• The servlet is responsible for setting the type of context
that would be include in the HTTP packets that will be sent
back to the client.
– The kind of content determines the type of streams needed on the
client side in order to receive the data sent as part of the response.
– If the client does not know the type of the context, it can be
discovered from the headers of the incoming HTTP packets
(received by the client)
• The various content types are defined in MIME –
Multipart Internet Mail Protocol
8
Servlet Context
• There are many different MIME content types i.e.
– text/html : refers to HTML text data
– text/plain : refers to plain text documents
– image/gif : refers to the fact that a gif file will be produced and
sent
– application/octet-stream : refers to the fact that the data is in the
form of an executable or binary data.
– application/x-java : java program
– application/x-csh : UNIX C-shell program
– Etc.
• The complete MIME types can be found on the Internet by Googling
MIME
9
Getting Info from Request
Objects
• The Request object contains information extracted
from the HTTP packets received from the client
by the web server (web container).
• Such information includes:
– Parameters that are passed from the client to the servlet.
– Objects and their attributes.
– Information about the protocol used to communicate between the
client and the server.
10
Getting Info from Request
Objects
–
–
–
–
–
Information about the client.
Information about the server.
The type of request (GET or POST).
The type of content (MIME)
Other
11
Information placed on Response
Objects
• Content type returned by the response to the client (i.e. content
generated by a servlet , sent to the web container, web container
extracts the data from the response object and inserts it in the HTTP
packets to be sent to the client)
• The data sent by the server to the client.
• Status codes that indicate why a request could not be honored.
• Session id.
• Cookies (files to be sent to the Browser and reside in local client
environment).
• Information about the client and the server.
• Other.
12
Filters
• Programs that are used to:
– Authenticate a request
– Modify a request or a response
– Block the request and response form going through.
• A web resource can be filtered by one or more filter
programs.
• Filters are used by using the Filter interface and overriding
its doFilter method (javax.servlet package).
• The web container decides how to use filter programs
based on filter mapping tags entered in the deployment
descriptor (web.xml).
13
HTTP Tunneling
• Refers to sending data back in a different protocol
than HTTP nevertheless enveloped by HTTP.
i.e. the server is sending data back to an applet
client program in a binary form or bytes.
• Or the server contacting another server, such as a
RMI server, to send data using the Remote
Method Invocation Protocol as the transport
protocol (or the RMI over IIOP transport
protocol).
14
HTTP Tunneling-Applets to
Servlets communication-GET
• Example of tunneling is an applet communicating with a servlet via
either GET or POST
• i.e Applet generates data for Web Component using GET / Reading
Binary data by an applet:
– Create a url object that identifies the host url.
URL url= new
URL(“http://localhost:8080/Bank/ShowBalance?id=custid”);
Notice that it is assumed that the HTTP method is GET since the
data is part of the URL.
Notice that the parameter is id but the value of it is held by
variable custid.
15
HTTP Tunneling-Applets to
Servlets communication-GET
Parameters are separated from the address part of URL by ?
Additional parameters are separated by &
URL url= new
URL(“http://localhost:8080/Bank/ShowBalance?id=custid&firstn=fn”);
The parameters are id and fn and their values are held by variables custid and fn
(notice the name/value pair for each parameter)
– Create a URLConnection object.
• Calling OpenConnection method returns a URLConnection object that can be
used to obtain streams .
URLConnection uc=url.openConnection();
16
HTTP Tunneling-GET
– Instruct the Browser not to cache the data:
uc.setCaches(false);
– Set other information in HTTP headers
uc.setRequestProperty(“header_name”, “value”);
– Use one of the input streams to read the response back
from the servlet.
• If the data from the servlet , for instance, was text/html (IN OTHER
WORDS THE CONTEXT WAS SET FOR text/html BY THE
SERVLET)
17
HTTP Tunneling-GET
BufferedReader in = new BufferedReader ( new
InputStreamReader (uc.getInputStream()));
String line;
while ( (line=in.readLine()) ! = null )
{
read the data and do something
}
in.close();
18
HTTP Tunneling
• Other types of context require different type of streams (for instance
object streams if the content is set for serializable objects)
• Note: HTTP packets have a Header part and a Body part. The header
contains standard named attributes whose values we can set.
• The String “header_name” in method setRequestProperty (see
previous slide) represents the name of the HTTP header attribute
whose value we are setting .
The http Header has pre defined fields whose value scan be set
programmatically by the applet (or an java application program
acting as clients. Or by a Browser).
19
HTTP Tunneling-Serializable Data
Received by the Client
– What if the data is binary in the form of object’ s data?
In other words serializable objects have been created by
the servlet and sent over the network to the applet
client.
– Serializable interface creates serializable objects using
Java’ s serialization protocol. Serialized objects can be
sent to another resource in binary form and deserialized
at the destination.
– To receive (by the Applet client as an example) the
serialized data sent by the servlet the code is formed
as follows by the client:
20
HTTP Tunneling-Serializable
Data Received by the Client
– Assume that we have a separate class on the server
side, that has a method which gets the data from the
data base puts it into a vector and that this class
implements the interface Serializable.. This class
returns a vector object which is serializable. The
serilizable object is sent by the servlet to the client.
– Create an ObjectInputStream
ObjectInputStream in = new ObjectInputStream (
uc.getInputStream()));
21
HTTP Tunneling-Serializable
Data Received by the Client
– Now read the object. As an example: The servlet got
data from a database and place it into a vector. The
servlet then serialized the vector and sent it as part of
the response. The code:
Vector myvector = (Vector)in. readObject();
deserializes the Object received into a Vector data type.
The object myvector now has the data sent by the
servlet.
22
HTTP Tunneling-Serializable
Data Sent by the Servlet
• What does the servlet have to do to send the
serialized data:
– Specify that the content is of binary format data.
res.setContentType(“application/x-java-serialized-object”);
– Create an object output stream
ObjectOutputStream out = new ObjectOutputStream
(res.getOutputStream() );
– Write the object into the output stream:
23
HTTP Tunneling-Serializable
Data
MyVectorClass mvc= new MyVectorClass();
Vector myvector = mvc.getVector();
out.write(myvector);
out.flush();
Where MyVectorClass is the class, on the server side, that
serializes the vector that contains the data.
24
Applet sends binary data to
Servlet as POST
•
Create URL object and URLConnection as in slides 5 and 6. The data ,
however, will not be part of the url this time.
• Tell system to permit applet to sent data (this is NOT in lieu of the required
certificate).
uc.setDoOutput(true);
• Create a ByteArrayOutputStream object
ByteArrayOutputStream bytestream= new ByteArrayOutputStream
(512);
512 bytes of data to be sent.
PrintWriter out =new PrintWriter(bytestream, true);
• Place data into a buffer:
Use either print if data is Strings or writeObject
25
Applet sends binary data to
Servlet as POST
•
Suppose it is a String that represents the data:
Need to url encode any parameters:
String val1= URLEncode(someval1);
String val2= URLEncode (someval2);
String data= “param1=“+val1+”param2=“+val2;
• Write the data into the stream:
out.print(data);
out.flush();
out.close(); // the data is written into the bytestream object
26
Applet sends binary data to
Servlet as POST
• Set the Content Length (required for POST)
uc.setRequestProperty(“Content-length”, String.valueOf(bytestream.size());
• Set the content type:
uc.setProperty(“Conetent-type”, “application/x-www-form-urlencoded”);
• Send the data out:
bytestream.writeTo(uc. getOutputStream());
27
Applications to Servlet
• If the client is an application program instead of
an applet the same procedure is followed to have
the application communicate either via GET or via
POST with the servlet.
• The only difference is that no Browser is needed
to execute the applet and the code for the
application did not come from another server but it
resided in the client’ s local system.
28
Sessions
•
•
Collaborating web resources in a server share information via objects. These
objects are maintained as attributes of 4 scope objects.
The attributes are accessible via methods like getAttribute or setAttribute.
Scope Object
Class
Accessible From
Web context
javax.servlet.ServletContext
Web components within a web context
Session
javax.servlet.http.HttpSession
Web components handling a request
that belongs to a session
Request
javax.servlet.SerletRequest
Web components that handle the
request
Page
javax.servlet.jsp.JspResponse
The JSP page that creates the
object
29
Session Management
• Sessions have time out periods if no request is received
from a client that has a session established
• The time out period can be set in the web.xml file that is in
the conf directory of the server (not the web.xml for your
web application)
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Timeout is set to 30 minutes in the above example.
30
Session Management
• Keeping track of a session via a session object is called server side
session tracking.
• This is different than using cookies which are files that are stored on
the client side by the server.
• The web container associates a session with a client. The web
container is responsible for generating a session id.
– A session identifier is created for each client.
– The identifier is sent to the client as a cookie and it is included or as an alternative
the web component (servlet) can include the session id in every response to the
client.
31
Session Management
• Create a session object in your web component:
HttpSession session = request.getSession(true);
Either a new object is created or an existing one is returned to the
servlet by the web container each time a request is made.
• You can store attribute_name/value pairs in the session object.
•
There are pieces of information that you can extract using the session object:
–
–
–
–
–
–
–
session.getID(); returns the session id for the client as a String.
session.isNew(); returns true if the client has never seen a session.
session,getCreationTime(); returns the time in milliseconds since the session was created.
session.getLastAccessedTime(); returns the time in milliseconds since the last request
generated a session.
session.getMaxInactiveInterval(); returns the time in milliseconds that the session can go
without access before it gets invalidated.
session.getAttributeName(String name); returns the object bound by the name in the session.
session.setAttribute(String name, Object obj); bounds an object obj by the String name. In the
session
32
Session Management
• Example of session management:
HttpSession session= request.getSession(true);
session.setAttribute("userName",request.getParameter("
myname"));
-----We store in the session object, as an object, the name
retrieved from parameter myname (assuming that the user
has entered a name captured by myname).
33
Session Management
-------Later on we check for the session:
session = request.getSession(true);
if (session.getAttribute("userName") == null)
{ session.setAttribute("userName", "Stranger"); }
else
PrintWriter out = response.getWriter();
out.println("Welcome " + (String) session.getAttribute("userName")
+ "!");
34
Session Management
• Another example:
• Suppose class ShoppingCart stores selected items in a
shopping cart object.
• HttpSession session = request.getSession(true);
ShoppingCart cart =
(ShoppingCart)session.getAttribute(session.getId()); //
If the user has no cart, create a new one
if (cart == null) { cart = new ShoppingCart();
session.setAttribute(session.getId(), cart); }
The card object is associated with the particular session id
associated with the client.
35
Session Management
• Because an object can be associated with a session, the
Duke's Bookstore example keeps track of the books that a
user has ordered within an object. The object is type
ShoppingCart and each book that a user orders is stored in
the shopping cart as a ShoppingCartItem object.
• Retrieving the shopping cart from the session in order to
add new item in it:
HttpSession session = request.getSession(true);
ShoppingCart cart =
(ShoppingCart)session.getAttribute(session.getId());
36
Servlet calls other resources
• RequestDispatcher Object allows another resource to be
called:
Example of calling an html file from a servlet:
getServletContext().getRequestedDispatcher(“examples/appli
cations/bookstore/bookstore.html”);
Returns the html page .
• The resources called can be
–
–
–
–
Another servlet
A Java Server Page
Html
Other
37
Servlet calls other resources
• Two types of requests for resources:
–
Forward request
–
Include request.
Servlet 1
Request object from
container
Servlet 2
1. ……………….
2 …………………..
3 …………………..
4 …………………..
5…………………..
6…………………
…
.
Request/Response
objects sent to
servllet 2
1. ……………….
2 …………………..
3 …………………..
4 …………………..
5…………………..
6…………………
…
.
Response object to container
Forward Request
38
Servlet calls other resources
Servlet 1
Request object from
container
Servlet 2
1. ……………….
2 …………………..
3 …………………..
4 …………………..
5…………………..
6…………………
…
.
Response object to container
1. ……………….
2 …………………..
3 …………………..
4 …………………..
5…………………..
6…………………
…
.
Request/Response objects
sent to servllet 2.
Servlet 2 return s objects to
calling servlet.
Include Request
39
Servlet calls other resources
• Forwarding using Dispatcher object:
Servlet1:
1. HttpSession session=request.getSession(true);
………..do something with request and response………….
2.
RequestDispatcher dispatcher=
getServletContext().getRequestDispatcher(“/AnotherServlet”);
3. dispatcher.forward(request, response);
Servlet 2:
After execution of line 3 servler AnotherServlet starts execution of its
doGet or doPost method. It receives the request and response
obejcts with whatever information has been encapsulated, does its
tasks and proceeds to write into the proper streams using the
response object.
40
Servlet calls other resources
• Including using the Dispatcher object:
Servlet1:
1. HttpSession session=request.getSession(true);
………..do something with request and response………….
2.
Dispatcher dispatcher=
getSevletContext().getRequestDispatcher(“/AnotherServlet”);
3. dispatcher.include(request, response);
4. Other code
Servlet 2:
Servlet AnotherServlet receives the request and response objects after
execution of line 3. Adds information to the response object and finishes
its tasks. Servlet 1 captures the request and response objects returned
from servlet 2at the eend of line 3 execution.
It proceeds with line 4.
41
Servlet calls other resources
• Another approach besides the usage of the Dispatcher
object is to use the redirect command:
response.sendRedirect(String name_of_resource);
• Sends a temporary redirect response to a client using the
resource specified. The String passed in the argument can
be a URL.
– A slash / in the URL means that the resource is relative to the
servlet folder root (WEB_INF/classes).
– The response will be sent to the client by the redirected resource.
42
Servlet calls other resources
• A chain of servlets can be formed:
request
Servlet 1
Request/
response
Request/
response
Servlet 2
Request/
response
Servlet 3
response
Servlet 4
43
Servlet calls other resources
• Using Scope Objects
• Collaborating web components share information by means of objects
that are maintained as attributes of four scope objects. You access
these attributes using the [get|set]Attribute methods of the class
representing the scope.
•
•
•
•
Scope Objects
Session
Request
Page
44
POST type of communication between
an applet (or an application) and a
servlet
• Remember that:
– If POST is to be used then the client (an applet
for example) has to place the data in the body
of the HTTP packet.
– That means that the url approach where the
parameters and their values are part of the url
CAN NOT be used.
– It also means that the servlet must have
implemented the doPost method.
45
Session Tracking with Cookies
• Session tracking can be established with cookies.
– Cookies are files sent by the web server to the client
and stored in the client’s system.
– The server reads the files every time contact is made
and extracts information about the client.
– The Servlets Api can generate cookies via
Cookie mycookie=new Cookie(cookiename, value);
response.addCookie( mycookie );
Request.getCookies() receives an array of cookie sfrom
client.
46
Information on Servlets
• Further Information about Java Servlet Technology
• For more information on Java Servlet technology, see:
• Java Servlet 3.0 specification:
http://jcp.org/en/jsr/detail?id=315
• The Java Servlet web site:
http://java.sun.com/products/servlet
47
Study Guide
• WBAD TEXT: Chapter 8.
• Java EE6 Tutorial- Part II Chapter 10.
• Read examples from course’ s web site and
implement them on Tomcat.
48
Download