Vous êtes sur la page 1sur 12

Java-Programming

*Short-Notes

Q.What are different way by which session can be tracked?

1. What is Session Tracking?


There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In
particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't
easily remember previous transactions. This makes applications like shopping carts very
problematic: when you add an entry to your cart, how does the server know what's already in
your cart? Even if servers did retain contextual information, you'd still have problems with ecommerce. When you move from the page where you specify what you want to buy (hosted on
the regular Web server) to the page that takes your credit card number and shipping address
(hosted on the secure server that uses SSL), how does the server remember what you were
buying?
There are three typical solutions to this problem.
1. Cookies. You can use HTTP cookies to store information about a shopping session, and
each subsequent connection can look up the current session and then extract information
about that session from some location on the server machine. This is an excellent
alternative, and is the most widely used approach. However, even though servlets have a
high-level and easy-to-use interface to cookies, there are still a number of relatively
tedious details that need to be handled:
o Extracting the cookie that stores the session identifier from the other cookies
(there may be many, after all),
o Setting an appropriate expiration time for the cookie (sessions interrupted by 24
hours probably should be reset), and
o Associating information on the server with the session identifier (there may be far
too much information to actually store it in the cookie, plus sensitive data like
credit card numbers should never go in cookies).
2. URL Rewriting. You can append some extra data on the end of each URL that identifies
the session, and the server can associate that session identifier with data it has stored
about that session. This is also an excellent solution, and even has the advantage that it
works with browsers that don't support cookies or where the user has disabled cookies.
However, it has most of the same problems as cookies, namely that the server-side
program has a lot of straightforward but tedious processing to do. In addition, you have to
be very careful that every URL returned to the user (even via indirect means like
Location fields in server redirects) has the extra information appended. And, if the user
leaves the session and comes back via a bookmark or link, the session information can be
lost.
1

3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT
TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is
submitted, the specified name and value are included in the GET or POST data. This can be
used to store information about the session. However, it has the major disadvantage that it
only works if every page is dynamically generated, since the whole point is that each
session has a unique identifier.
Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level
interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies if
the browser supports them, but automatically revert to URL-rewriting when cookies are
unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of the
details, doesn't have to explicitly manipulate cookies or information appended to the URL, and is
automatically given a convenient place to store data that is associated with each session.

2. The Session Tracking API


Using sessions in servlets is quite straightforward, and involves looking up the session object
associated with the current request, creating a new session object when necessary, looking up
information associated with a session, storing information in a session, and discarding completed
or abandoned sessions.

2.1 Looking up the HttpSession object associated with the current request.
This is done by calling the getSession method of HttpServletRequest. If this returns null,
you can create a new session, but this is so commonly done that there is an option to
automatically create a new session if there isn't one already. Just pass true to getSession. Thus,
your first step usually looks like this:
HttpSession session = request.getSession(true);

2.2 Looking up Information Associated with a Session.


objects live on the server; they're just automatically associated with the requester
by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects have a
builtin data structure that let you store any number of keys and associated values. In version 2.1
and earlier of the servlet API, you use getValue("key") to look up a previously stored value.
The return type is Object, so you have to do a typecast to whatever more specific type of data
was associated with that key in the session. The return value is null if there is no such attribute.
In version 2.2, getValue is deprecated in favor of getAttribute, both because of the better
naming match with setAttribute (the match for getValue is putValue, not setValue), and
because setAttribute lets you use an attached HttpSessionBindingListener to monitor values,
while putValue doesn't. Nevertheless, since few commercial servlet engines yet support version
2.2, I'll use getValue in my examples. Here's one representative example, assuming
ShoppingCart is some class you've defined yourself that stores information on items being
purchased.
HttpSession

HttpSession session = request.getSession(true);


ShoppingCart previousItems =

(ShoppingCart)session.getValue("previousItems");
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
}

In most cases, you have a specific attribute name in mind, and want to find the value (if any)
already associated with it. However, you can also discover all the attribute names in a given
session by calling getValueNames, which returns a String array. In version 2.2, use
getAttributeNames, which has a better name and which is more consistent in that it returns an
Enumeration, just like the getHeaders and getParameterNames methods of
HttpServletRequest.
Although the data that was explicitly associated with a session is the part you care most about,
there are some other pieces of information that are sometimes useful as well.

getId. This method returns the unique identifier generated for each session. It is
sometimes used as the key name when there is only a single value associated with a
session, or when logging information about previous sessions.
isNew. This returns true if the client (browser) has never seen the session, usually
because it was just created rather than being referenced by an incoming client request. It
returns false for preexisting sessions.
getCreationTime. This returns the time, in milliseconds since the epoch, at which the
session was made. To get a value useful for printing out, pass the value to the Date
constructor or the setTimeInMillis method of GregorianCalendar.
getLastAccessedTime. This returns the time, in milliseconds since the epoch, at which
the session was last sent from the client.
getMaxInactiveInterval. This returns the amount of time, in seconds, that a session
should go without access before being automatically invalidated. A negative value
indicates that the session should never timeout.

2.3 Associating Information with a Session


As discussed in the previous section, you read information associated with a session by using
getValue (or getAttribute in version 2.2 of the servlet spec). To specify information, you use
putValue (or setAttribute in version 2.2), supplying a key and a value. Note that putValue
replaces any previous values. Sometimes that's what you want (as with the referringPage entry
in the example below), but other times you want to retrieve a previous value and augment it (as
with the previousItems entry below). Here's an example:
HttpSession session = request.getSession(true);
session.putValue("referringPage", request.getHeader("Referer"));
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems == null) {
previousItems = new ShoppingCart(...);
}
String itemID = request.getParameter("itemID");
previousItems.addEntry(Catalog.getEntry(itemID));

// You still have to do putValue, not just modify the cart, since
// the cart may be new and thus not already stored in the session.
session.putValue("previousItems", previousItems);

Q. What is servlet life cycle?

The Life Cycle of a Servlet


Each servlet has the same life cycle:

A server loads and initializes the servlet

The servlet handles zero or more client requests

The server removes the servlet


(some servers do this step only when they shut down)

Initializing a Servlet
When a server loads a servlet, the server runs the servlet's init method. Initialization completes
before client requests are handled and before the servlet is destroyed.
Even though most servlets are run in multi-threaded servers, servlets have no concurrency issues
during servlet initialization. The server calls the init method once, when the server loads the
servlet, and will not call the init method again unless the server is reloading the servlet. The
server can not reload a servlet until after the server has destroyed the servlet by calling the
destroy method.

Interacting with Clients


After initialization, the servlet is able to handle client requests. This part of the servlet life cycle
was handled in the previous lesson.

Destroying a Servlet
Servlets run until the server are destroys them, for example, at the request of a system
administrator. When a server destroys a servlet, the server runs the servlet's destroy method.
The method is run once; the server will not run that servlet again until after the server reloads
and reinitializes the servlet.
When the destroy method runs, another thread might be running a service request. The
Handling Service Threads at Servlet Termination lesson shows you how to provide a clean
shutdown when there could be long-running threads still running service requests.

Q. What are different interfaces used in JDBC?


JDBC Interface
The following figure shows the core API interfaces in the JDBC specification and how they all tie up
together. These interfaces are implemented in the

java.sql
package.

The core API is also composed of a set of classes apart from interfaces, and these classes and
interfaces work together and are linked as shown in the diagram below:

All the statements in the JDBC interface eventually execute SQL to produce a ResultSet, and hence
the Statement class is a parent to all the other Statement classes. And all the statements are
executed using the underlying Connection to the database.
A Statement object is used to send SQL statements to a database. There are actually three kinds of

Statement objects, all of which act as containers for executing SQL statements on a given
connection: Statement, PreparedStatement, which inherits from Statement, and

CallableStatement, which inherits from PreparedStatement. They are specialized for sending
particular types of SQL statements: A Statement object is used to execute a simple SQL statement
with no parameters, a PreparedStatement object is used to execute a pre-compiled SQL statement
with or without IN parameters, and a CallableStatement object is used to execute a call to a
database stored procedure. We will start out by discussing the Statement object and then move onto
the more advanced PreparedStatement and CallableStatement statement objects.
The following diagram depicts the role of a class called DriverManager in a typical JDBC application.
The DriverManager acts as the bridge between a Java application and the backend database. When
the getConnection() method of this class is called, the DriverManager decides which JDBC driver
to use for connecting to the relevant connection request.

Q. What is Jar file? How it is created?


What is a JAR File?
Java Archive (JAR) files are compressed files into which you can store many files. If you place the many
classes that your application, or applet need in a JAR file, you reduce the size of your distributabels.
To create a JAR file, go to the directory where your files are located and type:

jar -cf ajarfile.jar *.*


and every file and directory in the current directory will be in a file called ajarfile.jar.
If you like to see what the JAR tility adds to the jar file, type:

jar -cvf ajarfile.jar *.*


The "v" option sends the JAR utility to a verbose mode, printing out information about its activities.
If you want to extract the content of an existing JAR file, type:

jar -xf ajarfile.jar


Again, if you like to see files (or directoies) that the JAR utility extracts from the JAR file, use the "v"
option, as in:

jar -xvf ajarfile.jar


If you like see a table of content of a JAR file, type:

jar -tf ajarfile.jar


Again, you can use the "v" option to see some information about the files in the JAR file, as in:

jar -tvf ajarfile.jar


There are other options with the JAR utility, to see them just type:

jar
If you have a UNIX background, you might have realized the definite similariries beteen JAR options and
the options of UNIX tar utility.
Behrouz Fallahi

Problems with the JAR format


The Ant team found that most of their support calls related to JAR file creation have two
underlying causes.[citation needed]
The first relates to manifest creation, specifically how long lines in the manifest are wrapped.
This is a complex and somewhat ambiguous part of the specification. Ant wraps long lines at 68
characters and continues on the following line with a space at the front to indicate a continuation.
This is viewed as erroneous by people who have not read the specification in detail and believe
that the Classpath should be split at a file boundary, instead of partly across a file name.
Unfortunately, if that is done, the Java runtime does not detect a split line as the first line ends
before the 68 character boundary.
The second is WinZip converting upper-case files and directories to lower case.[1] If a user views
the contents of a JAR file using an older version[which?] of WinZip, a file such as
MANIFEST/MANIFEST.MF is converted to manifest/manifest.mf. This has been remedied in
modern[which?] versions of WinZip, which now respects file name case. Some mobile phone Java
runtimes appear to parse the manifest in ways that are incompatible with the specification, and
require a strict ordering of entries in the manifest. They also do not implement the line wrapping
algorithm correctly. This may imply a problem in the test-suite for the Java ME mobile Java
runtime.

Q. What is implicit object of Servlet?


JSP Implicit and Session Objects
In this JPS tutorial, you will learn how to program using JSP, JSP expressions and Implicit
Objects, JSP Session Object, methods of session object, getAttribute(String name),
getAttributeNames and isNew().
JSP expressions:
If a programmer wants to insert data into an HTML page, then this is achieved by making
use of the JSP expression.
General syntax:
The general syntax of JSP expression is as follows:

<%= expression %>


The expression is enclosed between the tags <%= %>
For example, if the programmer wishes to add 10 and 20 and display the result, then the
JSP expression written would be as follows:

<%= 10+20 %>

Implicit Objects:
Implicit Objects in JSP are objects that are automatically available in JSP. Implicit Objects
are Java objects that the JSP Container provides to a developer to access them in their
program using JavaBeans and Servlets. These objects are called implicit objects because
they are automatically instantiated.
There are many implicit objects available. Some of them are:
request:
The
class
or
the
interface
name
of
the
object
request
is
http.httpservletrequest.
The
object
request
is
of
type
Javax.servlet.http.httpservletrequest. This denotes the data included with the HTTP
Request. The client first makes a request that is then passed to the server. The requested
object is used to take the value from clients web browser and pass it to the server. This is
performed using HTTP request like headers, cookies and arguments.
response: This denotes the HTTP Response data. The result or the information from a
request is denoted by this object. This is in contrast to the request object. The class or the
interface name of the object response is http.HttpServletResponse. The object response
is of type Javax.servlet.http. >httpservletresponse. Generally, the object response is
used with cookies. The response object is also used with HTTP Headers.

Session: This denotes the data associated with a specific session of user. The class or the
interface name of the object Session is http.HttpSession. The object Session is of type
Javax.servlet.http.httpsession. The previous two objects, request and response, are
used to pass information from web browser to server and from server to web browser
respectively. The Session Object provides the connection or association between the client
and the server. The main use of Session Objects is for maintaining states when there are
multiple page requests. This will be explained in further detail in following sections.
Out: This denotes the Output stream in the context of page. The class or the interface
name of the Out object is jsp.JspWriter. The Out object is written:
Javax.servlet.jsp.JspWriter
PageContext: This is used to access page attributes and also to access all the namespaces
associated with a JSP page. The class or the interface name of the object PageContext is
jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext
Application: This is used to share the data with all application pages. The class or the
interface name of the Application object is ServletContext. The Application object is
written: Javax.servlet.http.ServletContext
Config: This is used to get information regarding the Servlet configuration, stored in the
Config object. The class or the interface name of the Config object is ServletConfig. The
object Config is written Javax.servlet.http.ServletConfig
Page: The Page object denotes the JSP page, used for calling any instance of a Page's
servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page
object is written: Java.lang.Object
The most commonly used implicit objects are request, response and session objects

JSP Session Object


The previous section listed implicit objects available in JSP and detailed each of the methods
of request object and response object. This section details the Session Object and the
methods
available
with
syntax
and
explanation
on
each.
Session Object denotes the data associated with a specific session of user. The class or the
interface name of the object session is http.HttpSession. The object session is written as:
Javax.servlet.http.httpsession.
The previous two objects, request and response, are used to pass information from web
browser
to
server
and
from
server
to
web
browser
respectively.
The Session Object provides the connection or association between the client and the
server. The main use of Session Objects is to maintain states when there are multiple page
requests.
The main feature of session object is to navigate between multiple pages in a application
where variables are stored for the entire user session. The session objects do not lose the
variables and the value remains for the user session. The concept of maintenance of

10

sessions can be performed by cookies or URL rewriting. A detailed approach of session


handling will be discusses in coming sections.

Methods of session Object:


There are numerous methods available for session Object. Some are:

getAttribute(String name)
getAttributeNames
isNew()
getCreationTime
getId
invalidate()
getLastAccessedTime
getMaxInactiveInterval
removeAttribute(String name)
setAttribute(String, object)

Detailed usage with syntax and example with explanation of each of these methods.

getAttribute(String name):
The getAttribute method of session object is used to return the object with the specified
name given in parameter. If there is no object then a null value is returned.
General syntax of getAttribute of session object is as follows:
session.getAttribute(String name)
The value returned is an object of the corresponding name given as string in parameter. The
returned value from the getAttribute() method is an object written: java.lang.Object.
For example:

String exforsys = (String) session.getAttribute("name");


In the above statement, the value returned by the method getAttribute of session object
is the object of name given in parameter of type java.lang. Object and this is typecast to
String data type and is assigned to the string exforsys.

getAttributeNames:
The getAttributeNames method of session object is used to retrieve all attribute names
associated with the current session. The name of each object of the current session is
returned. The value returned by this method is an enumeration of objects that contains all
the unique names stored in the session object.
General Syntax:
session.getAttributeNames()

11

The returned value by this method getAttributeNames() is Enumeration of object.


For example:

exforsys = session.getAttributeNames( )
The above statement returns enumeration of objects, which contains all the unique names
stored in the current session object in the enumeration object exforsys.

isNew():
The isNew() method of session object returns a true value if the session is new. If the
session is not new, then a false value is returned. The session is marked as new if the
server has created the session, but the client has not yet acknowledged the session. If a
client has not yet chosen the session, i.e., the client switched off the cookie by choice, then
the session is considered new. Then the isNew() method returns true value until the client
joins the session. Thus, the isNew() method session object returns a Boolean value of true
of
false.
General syntax of isNew() of session object is as follows:
session.isNew()
The returned value from the above method isNew() is Boolean

12

Vous aimerez peut-être aussi