• In a broad term, an enterprise means a business
organization. The functionality of the organization
may limited to one s...
•

Each business organization has its own set of
rules and policies

•

Organization may have different set of activities
...
•

A well designed E-app must meet the
following goals:

•

Robustness : - Should have no or less
number of bugs.

•

Scal...
Followings are the advantage of JAVA in Eprogramming
•

Platform Independent : - Wide ranging
scattered enterprise informa...
A software application composition can be broken
down into three fundamental concerns or logical
layers.
•

The UI : - Thi...
The UI

The Business Rule

Data Access

THE SINGLE TIER ARCHITECTURE
•

All the concerns are deployed on a single
machine.

•

Strictly for single user

•

Easy to develop and maintain.

 Mu...
The UI

Request

Data Access

The Business Layer

The 2 tier architecture
•

Data can be shared between multiple users.

•

Multi-user system

 The centralized database system may be
the bottlene...
The UI

Request

Request

Data Access

Response

The Business Layer

Response

The 3 tier architecture
•

Data can be shared between multiple users.

•

Multi-user system

•

Less number of resource is consumed on
client side...
C1
EJB container

C3

C2

EIS

Web Container
In JEE app, containers are the central theme. A
container provides the runtime environment for
various component of JEE ap...
There are four types of container
1. EJB Container : It manages the execution
of all the enterprise bean for one JEE
appli...
HTTP is also known as Hyper-Text Transfer
Protocol. It is an application level protocol. It is
the mode by which web pages...
A HTTP transaction begins with a request from the client’s
browser and ends with a response from the server. The
HTTP requ...
Whenever client need to send some request to
the server it uses some HTTP specific method.
HTTP 1.0 defines only two metho...
Method

Description

POST

It is normally used in
HTML forms. Post is
used to transfer a block
of data to the server in
th...
Method

Description

DELETE

This method is used to
delete a document from
the server. The
document is identified
by the U...
Similar to HTTP Request , HTTP response
consists of three parts:
1. Protocol Status code Description
2. Response Header

3...
Client

Machine

Prepare
HTTP
Request

port
Convert
response object
to HTTP
response

Process &
Prepare response
Object

S...
A servlet is a java based server side
technology runs inside a container called
servlet engine.
Servlet interacts with cli...
From the definition it is clear that a servlet is a
java class. So,
import javax.servlet.http.HttpServlet;

public class M...
Receive
Request

Is
servlet
loaded

no

yes

Is
servlet
current

yes
Process request

no

Load Servlet
Send Response
Receive
Request

Is
servlet
loaded

no

yes

Is
servlet
current

No request for long
time
Call destroy()

yes

no

Call in...
JEE application requires a certain fixed directory
structure so that the server can identify and
locate resources in the a...
1. The Root :- The name of root directory is NOT
reserved. It depends upon the project name
possibly.
2. WEB-INF : - Its n...
The following are the steps required to run a servlet.
Step -1 : Write a Servlet

import javax.servlet.http.*;
import java...
Step -2 : Compile The Servlet
set
CLASSPATH=%CATALINA_HOME%commonlibservlet.j
ar;.
javac MyServlet.java
OR
javac classpath...
Step -3 : Create the directory structure for the project. The
root folder may have name Test.

Step -4 : Put the servlet c...
<!DOCTYPE web-app PUBLIC “-//Sun Microsystem,Inc.//
DTD Web Application 2.3//EN”
http://java.sun.com/dtd/web-app_2_3.dtd>
...
Step -6 : put the web.xml inside WEB-INF folder.
Step -7 : put the whole directory structure inside
%CATALINA_HOME%web-app...
Here
is
the
class
javax.servlet.http.HttpServlet

Hierarchy

javax.servlet.Servlet
implements
javax.servlet.GenericServlet...
HttpServlet class gets Life-cycle method from
GenericServlet class and GenericServlet provides
implementation of all metho...
The HttpServlet is basically used to handle HTTP
Request.
So HttpServlet defines some of the methods related to
HTTP. Here...
When a HTTP client sends a request using any HTTP
method (GET, POST, DELETE…) then the servlet engine
calls corresponding ...
Whenever client need to send some useful information to
the server then the message is sent in form of
Key=value
format. A...
Here are the methods provided by the
HttpServletRequest interface.
Sl. No

Method Signature

Description

1.

String getPa...
Sl. No

Method Signature

Description

3.

Enumeration
getParameterNames()

Returns all the keys
sent by the client. This
...
Sl. No

Method Signature

Description

5.

String getMethod()

Return the HTTP i.e.
GET, POST etc.
method using that this
...
Sl. No

Method Signature

Description

7.

String getHeader(String
hname)

Return the value of the
header represented by
h...
Sl. No

Method Signature

Description

7.

InputStream getInputStream()

Return the inputstream
object if the request
cont...
import javax.servlet.*;
import javax.servlet.http.*;
2
import java.io.*;
public class CheckBoxHandler extends HttpServlet
...
Compile the servlet… Put it at correct place inside the
directory structure. Map it inside web.xml and then create
an HTML...
The mapping in web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app … >

1

2
<servlet>
<servlet-name>setServlet</servl...
Sometimes it is required to initialize the servlet with some
parameters so that when the servlet is up and running the
par...
The initialization parameters are available to the servlet via
ServletConfig object. The GenericServlet override all the
a...
Here are the methods defined ServletConfig interface
Sl. No.

Method

Description

1.

String getInitParameter(String key)...
The context represents the run time environment in which
the servlet is running. The context is represented by the
Servlet...
Note that the <init-param> is not written inside any
<servlet> tag. Here is the way to obtain the initial
parameter

prote...
Here are some of the useful methods defined in
ServletContext interface.
Sl. No

Method

Description

1.

String getInitPa...
Sl. No

Method

Description

4.

void setAttribute(String
attribName,Object attrib)

Set the attribute to
the session

5.
...
HTTP is a stateless protocol. That means the server is not
going to maintain any state of the client and every request
fro...
Mainly in E-app programmer use two technique to
maintain the session.
i)

Cookie

ii)

HttpSession

The Cookie
The cookie ...
Here is piece of code……

protected void doGet(…. Req, …. Res ) …….
{
Cookie c=new Cookie(“MyCookie”,”Add Cart”);
Res.addCo...
protected void doGet(…. Req, …. Res ) …….
{
Cookies [] c=Req.getCookies();
for(int i=0;i<c.length;i++)
{
Cookie c1=c[i];
S...
Here are some useful method in cookie class.
Sl. No

Method

Description

1.

void setMaxAge(int exp)

Set age for cookie ...
•

The cookie is always stored at client side. That is why
the resources at server side is saved.

•

Cookie is a small te...
Cookie saves the server resources but gives a strong
chance to the client to control the session. This
disadvantage make t...
HttpSession is an interface in javax.servlet.http
package. When the client first interact with the server it
does not have...
Here is the code snippet to show how to create a session.

protected void doGet(…… request, ….. response)
throws ….
{
// I...
Here is the code snippet to show how to create a session.

protected void doGet(……
response) throws ….

request,

…..

{
/...
The HttpSession interface provides some important
methods.

Sl. No.

Method Name

Description

1.

void setAttribute(Strin...
Sl. No.

Method Name

Description

3.

void removeAttribute(String
key)

Remove the object
associated with key
from the se...
JEE framework two ways to set the inactive age for the
session object.
1. Using the setMaxInactiveInterval(int age) method...
2. Using web.xml

<web-app…..>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Here ...
The java enterprise edition (Servlet Basic)
Upcoming SlideShare
Loading in …5
×

The java enterprise edition (Servlet Basic)

1,231 views

Published on

Published in: Education, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,231
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
36
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

The java enterprise edition (Servlet Basic)

  1. 1. • In a broad term, an enterprise means a business organization. The functionality of the organization may limited to one single unit or may be distributed over multiple units and possibly units are situated at geographically different location. Also different unit follows different policies and rules. To manage these diversities with automation requires lot of effort. One single bug can harm the organization.
  2. 2. • Each business organization has its own set of rules and policies • Organization may have different set of activities • An enterprise programming facilitate various activities in an enterprise by following rules and policies. • In another word, enterprise application are one which helps an enterprise to manage its various activities.
  3. 3. • A well designed E-app must meet the following goals: • Robustness : - Should have no or less number of bugs. • Scalability and Performance :- Scalability refers to the term that the potential for an application to support increased load, given the appropriate hardware. The E-app must be designed in such a manner that it should not degrade its performance if load increases suddenly. • Maintainable & extensible : - A well designed E-app should be easy maintainable. If bugs are reported the it should be removed easily. Also new features can be added easily.
  4. 4. Followings are the advantage of JAVA in Eprogramming • Platform Independent : - Wide ranging scattered enterprise information that too in disparate formats are available that may be spread across different platform. So we need to adopt a programming language which function evenly well throughout the enterprise. • Managed Object :- JEE application are container centric. Due to this property, JEE component utilize the infrastructure provided by the JEE server without the programmer being aware of it. • Reusability : - Java is OO language. Objects can be reused in many different ways to achieve different functionalities. • Modularity :-
  5. 5. A software application composition can be broken down into three fundamental concerns or logical layers. • The UI : - This is responsible for displaying stuff to the user and collecting data from the user. Also called Presentation Layer. • Processing:- In this layer, the application works and handles the important processing. This logical layer is called Business rule layer. • Data Storage land Access : - All non-trivial business applications need to read and store the data. The part of the software that is responsible for writing data to the source and reading it from the source is called Data Access Layer. On the basis of deployment of these three layers, the E-app can have the following architecture
  6. 6. The UI The Business Rule Data Access THE SINGLE TIER ARCHITECTURE
  7. 7. • All the concerns are deployed on a single machine. • Strictly for single user • Easy to develop and maintain.  Multiple user support is not available  Hard to share data across enterprise.
  8. 8. The UI Request Data Access The Business Layer The 2 tier architecture
  9. 9. • Data can be shared between multiple users. • Multi-user system  The centralized database system may be the bottleneck.  The client side resource consumption is very high and so the client is called FAT client.
  10. 10. The UI Request Request Data Access Response The Business Layer Response The 3 tier architecture
  11. 11. • Data can be shared between multiple users. • Multi-user system • Less number of resource is consumed on client side and hence client is called THIN client. • Easy for maintenance. • Extendable  There is no clear separation between presentation and logic. So hard to develop.
  12. 12. C1 EJB container C3 C2 EIS Web Container
  13. 13. In JEE app, containers are the central theme. A container provides the runtime environment for various component of JEE apps. It acts as a runtime interface between the application components and the low level platform specific functionalities. The JEE containers provides development, management and execution support for application components.
  14. 14. There are four types of container 1. EJB Container : It manages the execution of all the enterprise bean for one JEE application. 2. Web Container : A web container manages the execution of all JSP pages and servlet for one JEE application. 3. Application Client Container : It manages the execution of all application client component for one JEE application. 4. Applet Container : It is a combination of web browser and java plug-in running together on the client machine.
  15. 15. HTTP is also known as Hyper-Text Transfer Protocol. It is an application level protocol. It is the mode by which web pages are communicated across the internet. Normally this protocol is used in communication between client and the server. Here are the steps followed in this protocol: 1. Connect 2. Request Client 3. Response 4. Close Server
  16. 16. A HTTP transaction begins with a request from the client’s browser and ends with a response from the server. The HTTP request consists of three components : 1. Method URI 2. Request Header 3. Protocol/Version Entire Body Example GET /servlet/default.jsp HTTP/1.1 Accept : text/plain ; text/html Accept-Language : en-gb Connection : Keep-Alive HOST : localhost User-Agent : Mozilla/4.0(Compatible; MSIE 4.01; windows 98) Content-Length : 33 LastName=Saurabh&FirstName=Atul
  17. 17. Whenever client need to send some request to the server it uses some HTTP specific method. HTTP 1.0 defines only two methods GET and POST. HTTP 1.1 defines five more. Method Description GET GET is the simplest and most used method. GET simply retrieves the data identified by the URI. HEAD This is similar to GET but it only retrieves the HTTP header and not the body.
  18. 18. Method Description POST It is normally used in HTML forms. Post is used to transfer a block of data to the server in the entire body of the request OPTIONS The OPTIONS method is used to query a server about the capabilities it provides. PUT It is complementary of GET. It stores the entire body at a location specified by the URI.
  19. 19. Method Description DELETE This method is used to delete a document from the server. The document is identified by the URI. TRACE It is used to trace the path of the request through firewall and multiple proxy server.
  20. 20. Similar to HTTP Request , HTTP response consists of three parts: 1. Protocol Status code Description 2. Response Header 3. Entire Body Example HTTP/1.1 200 OK Server : Microsoft IIS/4.0 Date : Mon 3, jan 2007 13:34:60 IST Content-Type : text/html Content-Length : 112 <html> <head><title>Example</title></head> <body>Welcome</body></html>
  21. 21. Client Machine Prepare HTTP Request port Convert response object to HTTP response Process & Prepare response Object Server Container Request Convert to object
  22. 22. A servlet is a java based server side technology runs inside a container called servlet engine. Servlet interacts with client via a requestresponse model based on HTTP. For programming perspective a servlet is defined in two ways: 1. A servlet is a java class embedded with HTML code. 2. A servlet is a java class which extends javax.servlet.http.HttpServlet class.
  23. 23. From the definition it is clear that a servlet is a java class. So, import javax.servlet.http.HttpServlet; public class MyServlet extends HttpServlet { }
  24. 24. Receive Request Is servlet loaded no yes Is servlet current yes Process request no Load Servlet Send Response
  25. 25. Receive Request Is servlet loaded no yes Is servlet current No request for long time Call destroy() yes no Call init() Call Service() Load Servlet Send Response
  26. 26. JEE application requires a certain fixed directory structure so that the server can identify and locate resources in the app. Some names are reserved and must not use elsewhere. Some of the directories are mandatory and some are optional. Here is the structure: Root(M) Reserved(M) Reserved(M) Important(M) Required for specific purpose(O)
  27. 27. 1. The Root :- The name of root directory is NOT reserved. It depends upon the project name possibly. 2. WEB-INF : - Its name is reserved and must be located inside the root directory. It is a private directory. 3. WEB-INF/classes : It contains all the java classes. 4. WEB-INF/web.xml : It is called deployment descriptor. 5. WEB-INF/lib : It contains all the external libraries possibly in form of JAR. 6. META-INF : It is optional. But it name is reserved. It contains project related configuration file. All the JSPs, HTML, JS, CSS etc go inside root directory.
  28. 28. The following are the steps required to run a servlet. Step -1 : Write a Servlet import javax.servlet.http.*; import java.io.*; import javax.servlet.*; public class MyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out=response.getWriter(); out.println(“Hello World!!!”); } }
  29. 29. Step -2 : Compile The Servlet set CLASSPATH=%CATALINA_HOME%commonlibservlet.j ar;. javac MyServlet.java OR javac classpath %CATALINA_HOME%commonlibservlet.jar MyServlet.java Here CATALINA_HOME represents the installation directory of Apache Tomcat.
  30. 30. Step -3 : Create the directory structure for the project. The root folder may have name Test. Step -4 : Put the servlet class in the WEB-INFclasses directory. Step -5 : Create the deployment descriptor i.e. web.xml and put the following content in this file….
  31. 31. <!DOCTYPE web-app PUBLIC “-//Sun Microsystem,Inc.// DTD Web Application 2.3//EN” http://java.sun.com/dtd/web-app_2_3.dtd> <web-app> <servlet> <servlet-name>Sample</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Sample</servlet-name> <url-mapping> /Sample</url-mapping> </servlet-mapping> </web-app>
  32. 32. Step -6 : put the web.xml inside WEB-INF folder. Step -7 : put the whole directory structure inside %CATALINA_HOME%web-apps Step -8 : Run the apache server using %CATALINA_HOMEbinstartup.bat Step -9: Call the servlet from the browser http://localhost:8080/Test/Sample
  33. 33. Here is the class javax.servlet.http.HttpServlet Hierarchy javax.servlet.Servlet implements javax.servlet.GenericServlet extends javax.servlet.http.HttpServlet of
  34. 34. HttpServlet class gets Life-cycle method from GenericServlet class and GenericServlet provides implementation of all method present inside Servlet interface. Here are the methods defined in Servlet interface • public void init(ServletConfig config) throws ServletException • public void service ( ServletRequest request, ServletResponse response) throws IOException, ServletException • public void destroy() • public String getServletInfo() • public ServletConfig getServletConfig()
  35. 35. The HttpServlet is basically used to handle HTTP Request. So HttpServlet defines some of the methods related to HTTP. Here are some of those methods…. 1. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException 2. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException 3. protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  36. 36. When a HTTP client sends a request using any HTTP method (GET, POST, DELETE…) then the servlet engine calls corresponding doXXX method. As for example when the client sends a request using DELETE HTTP method then servlet engine call doDelete method. Notice that all doXXX methods are very similar to service method. Here are the steps in handling request using servlet…. 1. The server get a request from the client. 2. The server converts the HTTP request into ServertRequest and handed over to the container. 3. The container invoke the servlet mapped by the URI. 4. The container create a thread for each client and the thread calls the service method. The ServletRequest object is handed over to the service method. 5. The service method in turns downcast the ServletRequest into HttpServletRequest and calls the doXXX method.
  37. 37. Whenever client need to send some useful information to the server then the message is sent in form of Key=value format. As form example firstname=rahul Here firstname is the key and rahul is the value. If there are many messages then each one is seperated by &. As for example firstname=rahul & lastname=dutta The HttpServletRequest parameter to the doXXX method represents the request sent by the client. This interface provides useful methods to fetch all the parameters sent by the client.
  38. 38. Here are the methods provided by the HttpServletRequest interface. Sl. No Method Signature Description 1. String getParameter(String key) Returns the value associated with the key. Useful when one key is associated with one value only. E.g. fetching the value submitted through the textfield, Dropdown box etc in HTML. 2. String [] getParameterValues(String key) Returns the array of values associated with the key. Useful when one key is associated with multiple values. E.g. fetching values from HTML checkbox.
  39. 39. Sl. No Method Signature Description 3. Enumeration getParameterNames() Returns all the keys sent by the client. This method can be used in conjunction with getParameter or getParameterValues. 4. RequestDispatcher getRequestDispatcher(String pageName) Returns RequestDispatcher object to either include the page referred by pageName in the current page or forward to page.
  40. 40. Sl. No Method Signature Description 5. String getMethod() Return the HTTP i.e. GET, POST etc. method using that this request is sent. 6. String getRequestURI() Returns the URI associated with this request.
  41. 41. Sl. No Method Signature Description 7. String getHeader(String hname) Return the value of the header represented by hname. 8. Enumeration getHeaderNames() Returns the names of all the headers sent by the client
  42. 42. Sl. No Method Signature Description 7. InputStream getInputStream() Return the inputstream object if the request contains some binary data. 8. HttpSession getSession() HttpSession getSession(boolean create) Returns the session object associated with the current request.
  43. 43. import javax.servlet.*; import javax.servlet.http.*; 2 import java.io.*; public class CheckBoxHandler extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out=response.getWriter(); String choices[] = request.getParameterValues(“myChoice”); out.println(“You have selected…<br>”); for(int i=0; i< choices.length;i++) { out.println(“ “+choices[i]+”<br>”); } } }
  44. 44. Compile the servlet… Put it at correct place inside the directory structure. Map it inside web.xml and then create an HTML form <body> <form method=“POST” actoin=“chkboxhndlr”> 3 <lable>Cricket</label><input type=“checkbox” value=“cricket” name=“myChoice”/> <lable>Basket Boll</label><input type=“checkbox” value=“basketboll” name=“myChoice”/> <lable>Hockey</label><input type=“checkbox” value=“hockey” name=“myChoice”/> <button type=“submit”>Submit</button> </form> </body>
  45. 45. The mapping in web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app … > 1 2 <servlet> <servlet-name>setServlet</servlet-name> <servlet-class> CheckBoxHandler </servlet-class> </servlet> 1 <servlet-mapping> <servlet-name>setServlet</servlet-name> <url-pattern>/ chkboxhndlr </url-pattern> </servlet-mapping> </web-app> 3
  46. 46. Sometimes it is required to initialize the servlet with some parameters so that when the servlet is up and running the parameters are available to it. This is generally called the configuration of the servlet and is limited to one servlet in context. The servlet is configured in web.xml i.e. Deployment Descriptor using <init-param> tag. Here is the code snippet : <servlet> <servlet-name>abc</servlet-name> <servlet-class>org.MyServlet</servlet-name> <init-param> <param-name>Nname</param-name> <param-value>Atul</param-value> </init-param> </servlet> A
  47. 47. The initialization parameters are available to the servlet via ServletConfig object. The GenericServlet override all the abstract method of Servlet interface. And HttpServlet class extends GenericServlet class. So the ServletConfig object can be obtained using getServletConfig() method. One can use getInitParameter(…) method to obtain the initial configuration values. Here is the code snippet. The servlet is configured in web.xml i.e. Deployment Descriptor using <init-param> tag. Here is the code snippit : protected void doGet(…… req, …..res) …. { ServletConfig g=getServletConfig(); String nName=g.getInitParameter(“Nname”); ……… } A
  48. 48. Here are the methods defined ServletConfig interface Sl. No. Method Description 1. String getInitParameter(String key) Returns the values associated with key 2. Enumeration getInitParameterNames() Returns all the keys defined for the configuration of this servlet 3. ServletContext getServletContext() Returns the context object for this servlet
  49. 49. The context represents the run time environment in which the servlet is running. The context is represented by the ServletContext object. Sometimes we need the set the configuration of all servlet running in an environment. That means the configuration is not limited to one particular servlet but available to all. In that case we need to talk to runtime environment and ServletContext will help. The initial configuration is also set in web.xml. Here is the way: <web-app> <context-param> B <param-name>forAll</param-name> <param-value>Good Morning</param-value> </context-param> …… </web-app>
  50. 50. Note that the <init-param> is not written inside any <servlet> tag. Here is the way to obtain the initial parameter protected ……… void doGet(…… req, …….res) { ServletConfig g=getServletConfig(); ServletContext c=g.getServletContext(); String msg=c.getInitParameter(“forAll”); ……………….. } B
  51. 51. Here are some of the useful methods defined in ServletContext interface. Sl. No Method Description 1. String getInitParameter(String key) Returns the initial parameters associated with the key set for the servlets. 2. Enumeration getInitParameterNames() Returns keys for all initial parameters set for the servlet. 3. RequestDispatcher getNamedDispatcher(String pageName) Returns the RequestDispatcher object for moving or including the page identified by pageName
  52. 52. Sl. No Method Description 4. void setAttribute(String attribName,Object attrib) Set the attribute to the session 5. Object getAttribute(String attribName) Returns the attribute associated with the attribName. 6. RequestDispatcher getRequestDispatcher(String pageName) Returns the RequestDispatcher object for moving or including the page identified by pageName
  53. 53. HTTP is a stateless protocol. That means the server is not going to maintain any state of the client and every request from the client is considered as the fresh request. But in some situation like Book Shopping it is necessary to maintain the state of the client because a client may add some book to its own cart. The state of client is loosely called its session. More precisely a session is defined as “A session is an uninterrupted request-response series between a client and the server”. The uninterrupted does not mean that client need to send the request immediately after it gets the response. Of course there might be a relaxation of time. But the server expect that client must communicate with it within the time limit.
  54. 54. Mainly in E-app programmer use two technique to maintain the session. i) Cookie ii) HttpSession The Cookie The cookie is a small text file in which the server keeps some information related to the client session and store on the client local hard disk. Here are the steps when session is managed by cookie. 1) The server prepare a cookie at some point of time and add it to the response. That means when the client browser get some response it also get the cookie. The browser store the cookie at its local hard disk. Normally the server stores time span, date of creation etc. information in the cookie.
  55. 55. Here is piece of code…… protected void doGet(…. Req, …. Res ) ……. { Cookie c=new Cookie(“MyCookie”,”Add Cart”); Res.addCookie(c); } 2) Next time when the browser sends a request to the server, it also sends the cookie to the server. Now it’s the duty of the server to get cookie from the request and perform some analysis task (possibly).
  56. 56. protected void doGet(…. Req, …. Res ) ……. { Cookies [] c=Req.getCookies(); for(int i=0;i<c.length;i++) { Cookie c1=c[i]; String value=c1.getValue(); } }
  57. 57. Here are some useful method in cookie class. Sl. No Method Description 1. void setMaxAge(int exp) Set age for cookie in seconds 2. void setValue(String value) Set the value in cookie 3. int getMaxAge() Return the life span of the cookie in seconds 4. String getValue() Returns the value set in the cookie.
  58. 58. • The cookie is always stored at client side. That is why the resources at server side is saved. • Cookie is a small textual information which requires less bandwidth to travel back and forth. • It is always a chance that client may change the data written inside the cookie. So not reliable. • If the Cookie is deleted, by accident also, the session will be invalidated by the server.
  59. 59. Cookie saves the server resources but gives a strong chance to the client to control the session. This disadvantage make the cookie impractical to maintain cookie. Java provides one more mechanism to maintain client session. And the mechanism is HttpSession. HttpSession does not allow the client to control the session. The server has full control over the client’s session. Whenever client need to session start, the sever generate a unique id called session id. This session id is sent back to the client. Whenever the client send request to the server it also sends it own session id. The server then verify the session id against its own repository. If the id is valid and not invalidated the server provides the allocated resource to the client.
  60. 60. HttpSession is an interface in javax.servlet.http package. When the client first interact with the server it does not have the session id. The server tries to fetch the session id from the request. If the id is NOT available then the server will create a session object and generate the session id. And that is why the HttpServletRequest interface provides two method to retrieve and create the session. Sl. No. Method Name Description 1. HttpSession getSession() Always create a new session object. It does not check whether session id is present or not 2. HttpSession getSession(boolean create) If the create is true then a new session object is created. Otherwise the session object is retrieved from the request.
  61. 61. Here is the code snippet to show how to create a session. protected void doGet(…… request, ….. response) throws …. { // If this is the first request for maintaining the sesion. HttpSession s=request.getSession(); // A session object is created and id is generated. . . . }
  62. 62. Here is the code snippet to show how to create a session. protected void doGet(…… response) throws …. request, ….. { // for subsequent request from client HttpSession s=request.getSession(false); // An old session is fetched from the request. . . . }
  63. 63. The HttpSession interface provides some important methods. Sl. No. Method Name Description 1. void setAttribute(String key, Object value) Set any java object in the session object. This java object will remain in the session until either session is invalidated or server explicitly call removeAttribute 2. Object getAttribute(String key) Returns the java object set in the session with key.
  64. 64. Sl. No. Method Name Description 3. void removeAttribute(String key) Remove the object associated with key from the session object. 4. void setMaxInactiveInterval(int age) This method set the maximum time span in seconds for which the client may remain inactive. If the time span laspe the session object is destroyed. 5. void invalidate() Forcefully destroy the session.
  65. 65. JEE framework two ways to set the inactive age for the session object. 1. Using the setMaxInactiveInterval(int age) method of HttpSession interface. Example : protected void doGet(……. req, ……. resp) throws …. { HttpSession hs = req.getSession(); hs.setMaxInactiveInterval(3* 60); // set the inactive age of session as 3 min. } This configuration is available to one type of session. It is possible that other client may have different setting for session object.
  66. 66. 2. Using web.xml <web-app…..> <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-app> Here the 30 represent 30 min and NOT 30 sec. This configuration is valid for every session object.

×