Date post: | 14-Apr-2018 |
Category: |
Documents |
Upload: | sunil-kumar |
View: | 227 times |
Download: | 0 times |
of 86
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
1/86
6/2/20
Networking
Socket Programming
connecting processes
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
2/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
3/86
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
4/86
6/2/20
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 socketto server IP and Port number (this is the port to which clients
will connect)
Accept a new connection from client
returns a client socketthat 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 socketto 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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
5/86
6/2/20
Programming Client-Server in Java
Programming TCP Client-Server in Java
All the classes related to sockets are in the java.net package, so makesure to import that package when you program sockets.
All the input/output stream classes are in the java.io package, includethis 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
toconnect 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);
}
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
6/86
6/2/20
Programming TCP Client-Server in Java
If you are programming a server, then this is how you open a socket:
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.
ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
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 aninput stream to receive response from the server:
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(MyClient.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
DataInputStream input;
try {
input = new
DataInputStream(clientSocket.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
7/86
6/2/20
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:
The class PrintStream has methods for displaying textual representationof Java primitive data types. Its write and println methods are important.Also, you may want to use the DataOutputStream:
Many of its methods write a single Java primitive type to the output stream.The method writeBytes is a useful one.
PrintStream output;
try {
output = new PrintStream(MyClient.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
DataOutputStream output;
try {
output = new
DataOutputStream(MyClient.getOutputStream());
}
catch (IOException e) {System.out.println(e);
}
On the server side
you can use the class PrintStream to send information to the
client.
Note: You can use the class DataOutputStream as mentioned
previously.
PrintStream output;
try {
output = new PrintStream(clientSocket.getOutputStream());
}
catch (IOException e) {
System.out.println(e);}
Programming TCP Client-Server in Java
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
8/86
6/2/20
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:
On the server side:
try {
output.close();
input.close();
MyClient.close();
}
catch (IOException e) {
System.out.println(e);
}
try {
output.close();
input.close();clientSocket.close();
MyService.close();
}
catch (IOException e) {
System.out.println(e);
}
HTTP
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
9/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
10/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
11/86
6/2/20
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 morerecent 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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
12/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
13/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
14/86
6/2/20
User-Agent
Software product used by original client
= User-Agent:
= [/]
=
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
15/86
6/2/20
Authorization:
For Password and authentication schemes
Ex.
Authorization: user fred:mypassword
Authorization: kerberos kerberosparameters
ChargeTo:
Accounting information
Accounting system dependent
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
16/86
6/2/20
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 owningserver 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 ofdocument
client can then display cached version
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
17/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
18/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
19/86
6/2/20
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 ortrickery if it is needed
Maintaining program state
Hidden variables (
Sessions
Special header tags interpreted by the server
Used by ASP, PHP, JSP
Implemented at the language api level
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
20/86
6/2/20
Servlets
50% - Mtl Already there
Evolution of Enterprise Applications - Single Tier
Easy to manage - client side management is NOT required
Data consistency is easy and simple to achieve, as all components a
one place
As application size grows, difficult to maintain and reuse
DumbTerminal 1
DumbTerminal 2
DumbTerminal 3
Contains
Business log
Presentatio
logic and da
access
Clients used only for data gathering
and output display
Mainframe
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
21/86
6/2/20
Evolution of Enterprise Applications - Two Tier (Client/Server)
1. Order fulfillment Application accessing Customer Information2. Customer care operations accessing same Customer DB
Database product independence
Difficult to maintain and update
Database Server
Data Access Layer
Business Logic and
Presentation Logic Layer
Evolution of Enterprise Applications - Three Tier
ExampleDART Application
Business logic can change more easily
Complexity introduced in the middle tier
Database
Server
Data Access LayerPresentation Logic Layer Business Logic
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
22/86
6/2/20
Evolution of Enterprise Applications - n Tier
Example - Wep Apps on Sparsh, like Leave System , Harmony
More loosely coupled
More reusable
Zero client management
Complexity in the middle tier
Database
Server
Data Access LayerPresentation Logic Business LogicThin Clients
Working of a Web Application
Internet uses Client/Server technology for its working
The world wide web uses the Browser as the client softwaand 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) a
Port No 80
The browser connects to Port No 80 of the specified Serve
Based on the request, the Web Server will deliver theappropriate page to the browser
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
23/86
6/2/20
Web Application model
Client Tier Middle TierEnterprise Information
System (EIS) Tier
application
browser
Web Container
ServletServlet
JSP
Database
SQL
Filesystem
Introduction
Servlets are modules that extend request/response-oriented 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 graphicaluser interface.
Servlets can be embedded in many different serversbecause the servlet API, which you use to writeservlets, assumes nothing about the server'senvironment or protocol.
Servlets are portable.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
24/86
6/2/20
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.
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 otherservers 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.
Uses for Servlets
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
25/86
6/2/20
Generic Servlets and HTTP Servlets
Every servlet must implement the javax.servlet.Servletinterface
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 Interface
methods to manage servlet
GenericServlet
implements Servlet HttpServlet
extends GenericServlet
exposes HTTP-specific
functionality
Servlet
extends
doGet()doPost()
service()
...
Override one or more of:
doGet()
doPost()
service()
...
Clas
s
Interface
Class
Class
Clas
s
extendsHttpServlet
implements
GenericServlet
UserServlet
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
26/86
6/2/20
Generic and HTTP Servlets
GenericServlet
service ( )
ServerClient
request
response
HTTPServlet
service ( )
HTTP ServerBrowser
request
response
doGet ( )
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 firstresponse.setContentType("text/html");
// then write the data of the response out = response.getWriter();
out.println("");
out.println(title);
out.println("");
out.println("" + title + "");
out.println("
This is output from SimpleServlet.");out.println("");
out.close();
}
}
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
27/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
28/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
29/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
30/86
6/2/20
3
Servlet Lifecycle
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
31/86
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
32/86
6/2/20
3
HttpServletRequest Interface
public String ServletRequest.getQueryString( ); returns the query string ofthe requst.
public String getParameter(String name): given the name of a parameter inthe query string of the request, this method returns the value.
String id = getParameter(id)
public String[ ] GetParameterValues(String name): returns multiple valuesfor the named parameter use for parameters which may have multiplevalues, 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 objectwith a list of all of the parameter names in the query string of the request.
HttpServletResponse Objects
An HttpServletResponse object provides two ways ofreturning data to the user:
The getWritermethod returns a Writer
The getOutputStream method returns aServletOutputStream
Use the getWritermethod to return text data to the
user, and the getOutputStreammethod for binarydata.
Closing the Writer or ServletOutputStream after yousend the response allows the server to know whenthe response is complete.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
33/86
6/2/20
3
HttpServletResponse Interface
public interface HttpServletResponse extendsServletResponse: The servlet engine provides an object that
implements this interface and passes it into th servlet through
the servicemethod 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(Hello world);
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.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
34/86
6/2/20
3
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 Writerresponse.setContentType("text/html");PrintWriter out = response.getWriter();// then write the responseout.println("" +
"Book Description" + ... );//Get the identifier of the book to displayString bookId = request.getParameter("bookId");if (bookId != null) {// fetch the information about the book and print it ... }out.println("");
out.close(); } ...}
Handling POST Requests
public class ReceiptServlet extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {
...// set content type header before accessing the Writerresponse.setContentType("text/html");PrintWriter out = response.getWriter( );// then write the responseout.println("" + " Receipt " + ...);out.println("Thank you for purchasing your books from us " +request.getParameter("cardname") + ...);out.close();}
...}
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
35/86
6/2/20
3
The Life Cycle of an HTTP Servlet
The web server loads a servlet when it is calledfor 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.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
36/86
6/2/20
3
Cookies in Java
A cookie has a name, a single value, and optional attributes such as acomment, 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 theHttpServletRequest.getCookies( )method. Several cookies might have thesame 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 cookiewith 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 ageof the cookie in seconds.
http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServletResponse.htmlhttp://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServletResponse.html7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
37/86
6/2/20
3
Processing Cookies with Java 2
public void setPath(java.lang.String uri): Specifies a path for the cookieto which the client should return the cookie. The cookie is visible to all thepages 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 towhich 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 (Contents of your shopping cart:);
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( );
}
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
38/86
6/2/20
3
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
Thejavax.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 asession 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.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
39/86
6/2/20
3
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 webapplication (ServletContext), so information stored
in one context will not be directly visible in another.
The Session object
A Session object
servelet engine
web server
Server host
Client host
request/response
servlet
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
40/86
6/2/20
4
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 nocurrent session and create is true, returns a new session. Ifcreate isfalse and the request has no valid HttpSession, this method returnsnull.
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 containingthe unique identifier assigned to this session. The identifier isassigned by the servlet container and is implementationdependent.
public java.lang.ObjectgetAttribute(java.lang.String name): returns the objectbound 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 ofString objects containing the names of allthe objects bound to this session.
public void removeAttribute(java.lang.String name):removes the object bound with the specified name from thissession. If the session does not have an object bound with thespecified name, this method does nothing.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
41/86
6/2/20
4
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 shoppingcart, 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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
42/86
6/2/20
4
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
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
43/86
6/2/20
4
Inter-Servlet Communication (Contd.)
The following are few methods that can be
used for communication between servletsMethod name Descr ipt ion
getServletContext() This method belongs to the interfacejavax.servlet.ServletConfig
public abstractServletContextgetServletContext()
This function returns the context of the servlet.
getRequestDispatcher() public abstract RequestDispatchergetRequestDispatcher(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 Descript ion
forward() 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 thefirst servlet with the current output.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
44/86
6/2/20
4
forward
The forwardmethod of the RequestDispatcherinterface 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 servletsservice method is called.
If the response has been committed, an
IllegalStateExceptionmust be thrown.
importjava.io.*;
importjavax.servlet.*;
importjavax.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);
}
}
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
45/86
6/2/20
4
include
The includemethod of the RequestDispatcherinterface 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. Anyattempt to do so should be ignored.
importjava.io.*;
importjavax.servlet.*;
importjavax.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);
}
}
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
46/86
6/2/20
4
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
47/86
6/2/20
4
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
48/86
6/2/20
4
Task 3: Write code for servlet 1
The first servlet uses the login table to validate theaccount 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 thesetAttribute() method
Task 4: Write the code for servlet 2
The second servlet:
Obtains the account number by using thegetAttribute() 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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
49/86
6/2/20
4
Task 5: Write the code for servlet 3
The third servlet:
Accesses the account number by using thegetAttribute() 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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
50/86
6/2/20
5
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.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
51/86
6/2/20
5
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
52/86
6/2/20
5
Getting attribute value from ServletContext
JSP
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
53/86
6/2/20
5
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.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
54/86
6/2/20
5
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!
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
55/86
6/2/20
5
Creating Dynamic Web Pages with JSP
The current date and time on
the Web server are:
The current date and time on
the Web server are:
Mon Jul 16 10:58:09 PDT 2007
JSP file Content sent to client
JSP script executes on the Web
server and the current date and
time are generated
Hello, World JSP Example
Hello World
Hello, World
Its
and all is well.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
56/86
6/2/20
5
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
57/86
6/2/20
5
Processing a Request for a JSP page
Servlets and JSPWhen 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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
58/86
6/2/20
5
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!
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
59/86
6/2/20
5
Retrieving Form Data
JSP provides request object
one of many objects created and maintained by container
we use to get info
returns query string exactly as would be appended to URL
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
60/86
6/2/20
The Three Kinds of JSP Elements
ScriptsWhat 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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
61/86
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
62/86
6/2/20
Sending Output Example
JSP output example 2
Your message is displayed using your preferred font format as
follows:
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 digitby convention, use lowercase for first letter, capitalize beginning of
each word
case sensitive!
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
63/86
6/2/20
Storing Form Information
Your major is
Using Basic JSP Techniques
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
64/86
6/2/20
Scripting With JSP Elements
Page DirectivesPage directive attributes apply to the entire JSP page:
OR
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
65/86
6/2/20
Import Attribute
Make Java classes available to the scripting environment
Use Java API to add power to your JSP scriptReference class without specifying package names
Using java.util.Date class
Without import:
If the class imported, then:
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
66/86
6/2/20
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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
67/86
6/2/20
Session Object Example
Session attribute
Is this a new session?
Current time:
The session created on :
Session Object Example
Session attribute
Is this a new session?
Current time:
The session created on :
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
68/86
6/2/20
Buffer Attribute
Specifies the size of the buffer used by the implicit out variable
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
Buffer attribute
The buffer attribute is set to "16kb"
Let's send some text to the HTML output stream
The content is buffered.
The buffered content is cleared from the buffer.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
69/86
6/2/20
Buffer Attribute Example
Buffer attribute
The buffer attribute is set to "none".
Let's send some text to the HTML output stream.
The content is not buffered.
The buffered content is not cleared.
isThreadSafe Attribute
Specify whether to allow more than one thread to execute the JSP code
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
70/86
6/2/20
7
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 DirectiveFormat
Alternative format (xml)
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!
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
71/86
6/2/20
7
Include Action
Form
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
requestedUpdates 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
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
72/86
6/2/20
7
Variable Duration Example
Variable duration
Use the counter variable declared in JSP
declaration
This page has been accessed
time.
times.
Variable Duration ExampleUse the counter variable declared in
JSP sriptlet
This page has been accessed
time.
times.
Reload this page
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
73/86
6/2/20
7
Implicit Objects
Implicit Objects
Objects created by the servlet container
application
session
request
response
exception
out
Config
pageContext
page
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
74/86
6/2/20
7
The JSP implicit application object is an instance of a java class thatimplements 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 implicit object
application object example
One.jsp
Two.jsp
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
75/86
6/2/20
7
The JSP implicit session object is an instance of a java class that implement
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.
session implicit object
One.jsp
two.jsp
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
76/86
6/2/20
7
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
response implicit object
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
77/86
6/2/20
7
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
request implicit object
Login.html
UserName:
Password:
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
78/86
6/2/20
7
request implicit object
LoginValidation.jsp
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.
out implicit object
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
79/86
6/2/20
7
out implicit object
Login.html
UserName:
Password:
out implicit object
LoginValidation.jsp
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
80/86
6/2/20
8
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.
exception 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.
config implicit object
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
81/86
6/2/20
8
config 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.
page implicit object
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
82/86
6/2/20
8
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.
pageContext implicit object
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.
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
83/86
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
84/86
6/2/20
8
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.
Session 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.
Application scope
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
85/86
6/2/20
8
JSP Standard actions
JSP Standard action are predefined tags which performsome 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.
Action element Description
s 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 orJSP page
Adds a parameter value to a request handed off to
another servlet
or JSP page using or
Generates HTML that contains the appropriate
browser-dependent
elements (OBJECT or EMBED) needed to execute
an applet with
the Java Plug-in software
JSP Standard actions
7/30/2019 Package -5 Networking, Applets, Http, Servlet, JSP, Struts
86/86
6/2/20
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: