SlideShare a Scribd company logo
1 of 58
CGICGI
Common Gateway InterfaceCommon Gateway Interface
Common Gateway Interface (CGI)
• As Fire walls are maintained in internet we can’t
access the resources of one network through the
other network systems, Fire wall allows only Http
Protocol.
• CGI is the standard way of communication
between Client and Application on the Server.
• It is an interface which allows to communicate
with an application on the server.
CGICGI
• CGI allows to generate Dynamic content in
response to the request from client.
• Programmes available on server side are called as
CGI scripts. These are loaded whenever it receives
client request.
• Scripting Language for CGI script must be in a
position to read and write from standard input &
output Streams.
• CGI is introduced with PERL(Practical Extraction
and Reporting Language) which is developed to
overcome the problems of c-language.
CGICGI
• CGI is commonly implemented by C, C++, PERL and
Java etc.
• With C and C++, CGI scripts are generated as
executable files and stores in CGI BIN directory
with executable permissions.
• C and C++ based CGI scripts will have problems like
Security problems, Platform Dependent, and lack
of proper support to Strings.
• PERL implementation of CGI scripts has overcome
the above problems.
CGICGI
• PERL is mainly used to generate Reports after
reading the data. Hence it has extended the
support of Strings.
• PERL is secured Language because of lack of
pointers.
• PERL is interpreter based language, where syntax
is mixture of shell script and C-Lang. As it is
interpreter the programme can be ported to any
platform without changes.
• As it is Interpreter based, the performance may
come down.
CGICGI
Drawbacks of CGI
1. CGI is slow since for every client request a new
process starts. If number of clients increases, less
memory is available which tends to bring down
the performance.
It becomes slower if the application is written in
interpreter based language.
It becomes unsafe if they are written in compiler
based languages.
CGICGI
Drawbacks of CGI
2. Fast CGI is better in performance when compare
to CGI since it uses concept of persistent process
( single process provides response to the many
clients if they request for same script).
This concept is implemented using Java but java
has lack of env variable reading support.
Accessing such variables may make a java
programme dependent on platform.
CGICGI
Drawbacks of CGI
3. Server Side Extension (API)
IIS  ISAPI
NServer  NSAPI
These have drawbacks as specific to web server
as script is based on API provided by the vendor
of web server.
They are not portable as specific to one web
server only.
CGICGI
SERVLETSERVLET
SERVLETSERVLET
Servlets are Java platform technology of choice for
extending and enhancing Web servers .
•component-based
•server- independent
•platform-independent
•protocol-independent
•fast and efficient
•most secured
• Servlets are used for building Web-based
applications, without the performance
limitations of CGI programs.
• Servlets have access to the entire family of Java
APIs, including the JDBC API to access enterprise
databases.
• Servlets can also access a library of HTTP-specific
calls and receive all the benefits of the mature
Java language, including portability,
performance, reusability, etc.
SERVLETSERVLET
WEB SERVER
JVM
SERVLET
CLEINT
Request
Response
Servlet Name +
parameters
DATA
BASE
Servlet context
SERVLETSERVLET
SERVLETSERVLET
•JVM loads the servlet on the request from client if
servlet is not loaded.
•Heavily used servlets has to be loaded on starting of
web server to avoid loading and creating instance on
every client request.
•On every client request a service method is called by
creating it as separate thread in JVM, i.e. every client
request has a thread created.
•Unloading of servlet depends on vender specification
i.e., unloads after response or if no response for a
specific amount of time etc.
SERVLETSERVLET
INSTANCECLASS
INIT
SERVICE
DESTROY
DOGETDOPOST
Life Cycle of SERVLETLife Cycle of SERVLET
Servlet is an API which is provided as servlet.jar
Servlet is an interface of package javax.servlet
javax.servlet.Servlet
javax.servlet.GenericServlet
javax.servlet.http.HttpServletFor HTTP protocol
SERVLETSERVLET
Methods to provide service
public void service(ServletRequest req ,
ServletResponse res) throws IOException,
ServletException
public void doGet(HttpServletRequest req ,
HttpServletResponse res) throws IOException,
ServletException
public void doPost(HttpServletRequest req ,
HttpServletResponse res) throws IOException,
ServletException
SERVLETSERVLET
import javax.servlet.*;
public class NewServlet extends GenericServlet
{
public void init(ServletConfig conf)
{initialisation code; }
public void service(ServletRequest req,
ServletResponse res) throws IOException,
ServletException {service
code;}
public void destroy() { destroy code; }
}
SERVLETSERVLET
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet
{
public void init(ServletConfig conf)
{initialisation code;}
public void service(HttpServletRequest req,
HttpServletResponse res) throws IOException,
ServletException {service code;}
public void destroy(){ destroy code;}
}
SERVLETSERVLET
HTTP Technology allows to request in two ways
GET : requested from address bar and information
parameters are given as Query String which is part of
URL and separated by ‘?’ GETURL?QueryString
POST : requested from form and large amount of
information can be send to input streams.
• POST is most preferred send large amount of data as
data gets truncated in GET request.
SERVLETSERVLET
public class NewServlet extends HttpServlet
{ public void init(ServletConfig conf) {init code;}
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException,
ServletException {Get Service
code;}
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws IOException,
ServletException {Post
Service code;}
public void destroy() {destroy code;}
}
SERVLETSERVLET
res.setContentType( “MIME TYPE”);
To set the header format of response
ServletOutputStream sos=res.getOutputStream();
To create OutputStream to send response
sos.println( “html tags/data” );
Method used to send the data with OutputStream
SERVLETSERVLET
MIME TypesMIME Types
text/plain
text/html
text/java
image/gif
image/jpg
image/bmp
audio/midi
audio/wav
audio/all
1.Create a Servlet and save that as
ServletName.java file.
2.Compile that from the place of creation.
3.Create a Deployment Descriptor with web.xml
file, which includes servlet name and servlet
mapping.
4.Deploy the class file and deployment descriptor
into web server with the specified process of
deployment of a web server.
SERVLETSERVLET
web.xmlweb.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>ServletName</servlet-name>
<servlet-class>ServletClassName</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletName</servlet-name>
<url-pattern>/vfolder/ServletName</url-pattern>
</servlet-mapping>
</web-app>
•The hierarchy structure to deploy the servlet file in
tomcat web server.
SERVLET DeploymentSERVLET Deployment
•war file has to be created to deploy the web
application into web server.
•Creating “application.war” is possible by “jar”
command
SERVLET DeploymentSERVLET Deployment
prompt> jar –cvf <war_filename> <info_folder>
Example:
C:erp:> jar –cvf erp.jar .WEB-INF
Requesting from ClientRequesting from Client
Call The servlet by using the URL in client
application (HTML Form, Browser AddressBar,
Applet etc.) as…..
http://HostIpAddress:PortNo/app_name/url-
pattern
Example:
http://localhost:8080/erp/register
http://127.0.0.1:8080/erp/login
Requesting from ClientRequesting from Client
Call The servlet by using HTML Form
<form
action=“http://IpAddress:port/application/vFilena
me” method=“post”>
<button type=“submit”>
</form>
Requesting from ClientRequesting from Client
Call The servlet by using Applet/Midlet
String ues=URLEncoder.encode(“url”);
URL u=new URL(ues);
URLConnection con=u.openConnection();
BufferedReader br=new BufferedReader(new
InputStreamReader(con.getInputStream());
String s=br.readLine();
ta.setText(s); //ta is TextArea
Request ParametersRequest Parameters
Enumeration e = req.getParameterNames()
To get parameter names sent with the request
String name = (String) e.getNextElement()
To get name stored in Enumeration Object
String[] s = req.getPrameter(String)
To get the parameter value of given name
String[] s = req.getPrameterValues(String)
To get multiple parameter values of given name
Request ParametersRequest Parameters
String user = req.getPrameter(“user”)
String pwd = req.getPrameter(“password”)
Note:
This will become hardcode of parameter names and no.
of parameter.
servlet may not work in case of any changes in
parameter names/numbers in client request.
Better to get all the names of parameters sent in
request and then get the values of each parameter
name.
Request ParametersRequest Parameters
Enumeration e = req.getParamenterNames();
while (e.hasMoreElements())
{
String name = (String)e.nextElement();
String value = req.getParamenter(name);
out.println(name + " = " + value);
}
Servlet ContainerServlet Container
A servlet container comprises essentially the
component of a web server that hosts and interacts
with Java servlets.
Web components (Servlet, JSP) run in a Web container
which provides system services to Web components.
Web container specifies a runtime environment for
web components that includes security, life-cycle
management, deployment, and other services.
Session TrackingSession Tracking
HTTPHTTP
•Http is a stateless protocol. Every request is treated
as request from a new user, even though the same
client is requesting.
•Http is stateless since the purpose of this protocol is
just to distribute the information and not to retain
information about client.
•Each time a client retrieves a Web page, it opens a
separate connection to the Web server, and the server
does not automatically maintain contextual
information about a client.
Session TrackingSession Tracking
•Session tracking is a mechanism that servlets use to
maintain state about a series of requests from the
same user (that is, requests originating from the same
browser) across some period of time.
•To maintain the information of client, Cookie is
invented by Netscape company.
•Cookie is a part of Http.
Session TrackingSession Tracking
URL rewriting is used by appending a unique ID after
the URL to identify the user.
Hidden <form> fields can be used to store a unique ID
for the session.
Cookies are small files that the servlet can store on the
client computer, and retrieve later.
Http Session is an alternative to cookies. It keeps the
session data available until browsing ends.
URL Rewriting
• Every local URL requested by user can be modified
dynamically by the servlet to include extra info
(session tracking info).
• Extra info can hold information for the session, e.g.
Session id, User Name etc.
e.g. URL with an additional parameter added on by
your code:
– http://server/MyServlet?sessionid=123
URL Rewriting
Example: banking application. Bank employee’s branch-id
is passed from one servlet to another to save re-entry
// Get the current employee and branch ids
String bid = req.getParameter(branchid);
String eid = req.getParameter(empid);
out.println(“<FORM ACTION = ”bankservlet?
branchid=“+bid+”&empid=“+eid+"">");
out.println("</FORM>");
Hidden Fields
•“Hidden” fields are added to a form which will not be
displayed on the browser
<form action=“/moviefinder” method=“post”>
<input type=“hidden” name=“pin” value=“420”>
•From servlets, there is no difference in hidden fields
and visible fields, both are request parameters only.
•The servlet retrieves the hidden fields by using
req.getParameter(“pin”) or
req.getParameterValues(“pin”)
Hidden Fields
Example:
String[] items = req.getParameterValues("item");
out.println("<FORM ACTION="someServlet" METHOD=POST>");
if (items != null)
for (int i = 0; i < items.length; i++){ out.println("<INPUT
TYPE=HIDDEN NAME="item“ VALUE=""+items[i]+"">");
}
out.println("Would you like to<BR>");
out.println("<INPUT TYPE=SUBMIT VALUE="Add More Items">");
out.println("<INPUT TYPE=SUBMIT VALUE="Check Out">");
out.println("</FORM>");
Cookies are name, valued objects which are created at
server and stored on client side by the server.
Cookie contents the information of client itself.
The next time client sends the request, cookie is also
send as part of request.
Bye default Cookie is stored as text file in
c:windowstemp
CookieCookie
Cookie
Every cookie has only one name and value
Cookie will be associated with Max Age, Domain Name,
Path and Comment
Limitations:
•Max size of cookie can be 4KB
•Max no. of cookies per site can be 20
•Not more than 300 cookies total
Max Age:
Default is up to destroying the browser.
-ve means valid till current session.
0 means deleting cookie on client side.
We can set the age of cookie explicitly as
24x60x60 for 1 day
2x24x60x60 for 2 days etc.
CookieCookie
Domain: Every cookie will have domain apart from
maximum age. Default of cookie is the domain from
which cookie is sent to the client.
Path: Cookie having a path will not be send to server if
request URL doesn't contain the cookie path.
Comment: Some user agents have facility to worn the
clients before accepting cookies. This working is
through a dialog which can also show comment of the
cookie.
CookieCookie
Cookie is a class present in javax.servlet.http package.
Constructor:
Cookie(String name, String value)
res.addCookie(c);
Cookie[ ] c = req.getCookies();
CookieCookie
Methods:
String n=c.getName()
String v=c.getValue()
Int t=c.getMaxAge() c.setMaxAge(int)
String p=c.getPath() c.setPath(String)
String com=c.getComment(),
c.setComment(String)
CookieCookie
String n = req.getParameter(“pname");
String v = req.getParameter(“pvalue”);
Cookie nc = new Cookie(n, v);
res.addCookie(nc);
Cookie[] old_cs = req.getCookies();
for(Cookie oc:old_cs)
res.addCookie(oc);
CookieCookie
if(v.equals(“bill”)
{
Double tbill=0.0;
Cookie[ ] pcs = req.getCookies();
for(Cookie c:pcs)tbill+=Double.valueOf(c.getValue());
Cookie tb=new Cookie(“tbill”, tbill.toString());
res.addCookie(tb);
}
CookieCookie
Advantages:
•Cookies can easily store more data than hidden fields
•Data is stored on the client computer, not on server which
saves space on the server and will not have any effect on
server performance.
Disadvantages:
•Data is stored on the client computer, this means the data is
neither safe nor secure
•Cookies are good for keeping session data, not user data
•Cookies may be discarded or the user may contact the
server from another computer
•Users can tell their browser to turn cookies off
CookieCookie
SessionSession
A Session begins when a client establishes a connection
with http server.
For every client an object will be created at server side
which is called as HttpSession.
Session is a concept which internally works with
cookie. It is called as Server Side Cookie.
HttpSession stores the information of client on the
server which is identified by the server by using cookie,
which is created and set by the web server (Servlet
Engine).
Session will have the features of storing and retrieving
the information.
Cookie is validated till the session is valid.
It is valid until the client is connected to server.
Session may also disposed if the client is idle for more
than a specific time, which is dependent on server
vendor/ Administrator.
Session object implements the interface of
HttpSession.
SessionSession
SessionSession
HttpSession ses = req.getSession();
Creates a new HttpSession object, or retrieves a
previous one
Creates a unique session ID
Makes a new cookie object
Associates the cookie with the session ID
Puts the cookie in the response (under the Set-Cookie
header)
HttpSession ses = req.getSession();
Enumeration e = ses.getAttributeNames();
while (e.hasMoreElements())
{
String n = (String)e.nextElement();
String v = ses.getAttribute(name).toString();
out.println(n + " = " + v);
}
SessionSession
Methods:
hs.removeAttribute(name);
hs.invalidate();
Boolean b=hs.isNew();
String id=hs.getId();
long t=hs.getCreationTime();
long t=hs.getLastAccessedTime();
SessionSession
Servlet to Servlet CommunicationServlet to Servlet Communication
res.encodeRedirectURL(“URL?QueryString”));
Example:
res.encodeRedirectURL(“http://server:8080/servlet/color
”));
res.encodeRedirectURL(“http://server:8080/color.html”))
;
All The Best
…. I Career Craft

More Related Content

What's hot

WebServices in ServiceMix with CXF
WebServices in ServiceMix with CXFWebServices in ServiceMix with CXF
WebServices in ServiceMix with CXFAdrian Trenaman
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIPRIYADARSINISK
 
Running gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesRunning gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesSungwon Lee
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Ajp notes-chapter-06
Ajp notes-chapter-06Ajp notes-chapter-06
Ajp notes-chapter-06Ankit Dubey
 
Web Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureWeb Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureToru Kawamura
 
Cloudy Open Source and DevOps
Cloudy Open Source and DevOpsCloudy Open Source and DevOps
Cloudy Open Source and DevOpsMatt O'Keefe
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6aminmesbahi
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1AkramWaseem
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful  Protocol BuffersJavaOne 2009 - TS-5276 - RESTful  Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful Protocol BuffersMatt O'Keefe
 
Web development with ASP.NET Web API
Web development with ASP.NET Web APIWeb development with ASP.NET Web API
Web development with ASP.NET Web APIDamir Dobric
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RSFahad Golra
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIEyal Vardi
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
 

What's hot (19)

WebServices in ServiceMix with CXF
WebServices in ServiceMix with CXFWebServices in ServiceMix with CXF
WebServices in ServiceMix with CXF
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
Oracle API Gateway Installation
Oracle API Gateway InstallationOracle API Gateway Installation
Oracle API Gateway Installation
 
Running gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesRunning gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on Kubernetes
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Ajp notes-chapter-06
Ajp notes-chapter-06Ajp notes-chapter-06
Ajp notes-chapter-06
 
Ftp servlet
Ftp servletFtp servlet
Ftp servlet
 
Web Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureWeb Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the future
 
Cloudy Open Source and DevOps
Cloudy Open Source and DevOpsCloudy Open Source and DevOps
Cloudy Open Source and DevOps
 
Listeners and filters in servlet
Listeners and filters in servletListeners and filters in servlet
Listeners and filters in servlet
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful  Protocol BuffersJavaOne 2009 - TS-5276 - RESTful  Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
 
Spring integration
Spring integrationSpring integration
Spring integration
 
Web development with ASP.NET Web API
Web development with ASP.NET Web APIWeb development with ASP.NET Web API
Web development with ASP.NET Web API
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
 
Aspdotnet
AspdotnetAspdotnet
Aspdotnet
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 

Similar to Servlet

Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet backdoor
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 

Similar to Servlet (20)

Servlets
ServletsServlets
Servlets
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Java servlets
Java servletsJava servlets
Java servlets
 
Servlets
ServletsServlets
Servlets
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
 
Servlet
Servlet Servlet
Servlet
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 

More from Rajesh Roky

File splitter and joiner
File splitter and joinerFile splitter and joiner
File splitter and joinerRajesh Roky
 
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILEINTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILERajesh Roky
 
The main purpose of the project is to manage the supermarket efficiently (rep...
The main purpose of the project is to manage the supermarket efficiently (rep...The main purpose of the project is to manage the supermarket efficiently (rep...
The main purpose of the project is to manage the supermarket efficiently (rep...Rajesh Roky
 
File Splitter Table of contents
File Splitter Table of contents File Splitter Table of contents
File Splitter Table of contents Rajesh Roky
 
FILE SPLITTER AND JOINER
FILE SPLITTER AND JOINERFILE SPLITTER AND JOINER
FILE SPLITTER AND JOINERRajesh Roky
 
Rainbow technology-ppt
Rainbow technology-pptRainbow technology-ppt
Rainbow technology-pptRajesh Roky
 

More from Rajesh Roky (8)

11. jdbc
11. jdbc11. jdbc
11. jdbc
 
wrapper classes
wrapper classeswrapper classes
wrapper classes
 
File splitter and joiner
File splitter and joinerFile splitter and joiner
File splitter and joiner
 
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILEINTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
 
The main purpose of the project is to manage the supermarket efficiently (rep...
The main purpose of the project is to manage the supermarket efficiently (rep...The main purpose of the project is to manage the supermarket efficiently (rep...
The main purpose of the project is to manage the supermarket efficiently (rep...
 
File Splitter Table of contents
File Splitter Table of contents File Splitter Table of contents
File Splitter Table of contents
 
FILE SPLITTER AND JOINER
FILE SPLITTER AND JOINERFILE SPLITTER AND JOINER
FILE SPLITTER AND JOINER
 
Rainbow technology-ppt
Rainbow technology-pptRainbow technology-ppt
Rainbow technology-ppt
 

Recently uploaded

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Recently uploaded (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

Servlet

  • 2. Common Gateway Interface (CGI) • As Fire walls are maintained in internet we can’t access the resources of one network through the other network systems, Fire wall allows only Http Protocol. • CGI is the standard way of communication between Client and Application on the Server. • It is an interface which allows to communicate with an application on the server. CGICGI
  • 3. • CGI allows to generate Dynamic content in response to the request from client. • Programmes available on server side are called as CGI scripts. These are loaded whenever it receives client request. • Scripting Language for CGI script must be in a position to read and write from standard input & output Streams. • CGI is introduced with PERL(Practical Extraction and Reporting Language) which is developed to overcome the problems of c-language. CGICGI
  • 4. • CGI is commonly implemented by C, C++, PERL and Java etc. • With C and C++, CGI scripts are generated as executable files and stores in CGI BIN directory with executable permissions. • C and C++ based CGI scripts will have problems like Security problems, Platform Dependent, and lack of proper support to Strings. • PERL implementation of CGI scripts has overcome the above problems. CGICGI
  • 5. • PERL is mainly used to generate Reports after reading the data. Hence it has extended the support of Strings. • PERL is secured Language because of lack of pointers. • PERL is interpreter based language, where syntax is mixture of shell script and C-Lang. As it is interpreter the programme can be ported to any platform without changes. • As it is Interpreter based, the performance may come down. CGICGI
  • 6. Drawbacks of CGI 1. CGI is slow since for every client request a new process starts. If number of clients increases, less memory is available which tends to bring down the performance. It becomes slower if the application is written in interpreter based language. It becomes unsafe if they are written in compiler based languages. CGICGI
  • 7. Drawbacks of CGI 2. Fast CGI is better in performance when compare to CGI since it uses concept of persistent process ( single process provides response to the many clients if they request for same script). This concept is implemented using Java but java has lack of env variable reading support. Accessing such variables may make a java programme dependent on platform. CGICGI
  • 8. Drawbacks of CGI 3. Server Side Extension (API) IIS  ISAPI NServer  NSAPI These have drawbacks as specific to web server as script is based on API provided by the vendor of web server. They are not portable as specific to one web server only. CGICGI
  • 10. SERVLETSERVLET Servlets are Java platform technology of choice for extending and enhancing Web servers . •component-based •server- independent •platform-independent •protocol-independent •fast and efficient •most secured
  • 11. • Servlets are used for building Web-based applications, without the performance limitations of CGI programs. • Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. • Servlets can also access a library of HTTP-specific calls and receive all the benefits of the mature Java language, including portability, performance, reusability, etc. SERVLETSERVLET
  • 12. WEB SERVER JVM SERVLET CLEINT Request Response Servlet Name + parameters DATA BASE Servlet context SERVLETSERVLET
  • 14. •JVM loads the servlet on the request from client if servlet is not loaded. •Heavily used servlets has to be loaded on starting of web server to avoid loading and creating instance on every client request. •On every client request a service method is called by creating it as separate thread in JVM, i.e. every client request has a thread created. •Unloading of servlet depends on vender specification i.e., unloads after response or if no response for a specific amount of time etc. SERVLETSERVLET
  • 16. Servlet is an API which is provided as servlet.jar Servlet is an interface of package javax.servlet javax.servlet.Servlet javax.servlet.GenericServlet javax.servlet.http.HttpServletFor HTTP protocol SERVLETSERVLET
  • 17. Methods to provide service public void service(ServletRequest req , ServletResponse res) throws IOException, ServletException public void doGet(HttpServletRequest req , HttpServletResponse res) throws IOException, ServletException public void doPost(HttpServletRequest req , HttpServletResponse res) throws IOException, ServletException SERVLETSERVLET
  • 18. import javax.servlet.*; public class NewServlet extends GenericServlet { public void init(ServletConfig conf) {initialisation code; } public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException {service code;} public void destroy() { destroy code; } } SERVLETSERVLET
  • 19. import javax.servlet.*; import javax.servlet.http.*; public class NewServlet extends HttpServlet { public void init(ServletConfig conf) {initialisation code;} public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {service code;} public void destroy(){ destroy code;} } SERVLETSERVLET
  • 20. HTTP Technology allows to request in two ways GET : requested from address bar and information parameters are given as Query String which is part of URL and separated by ‘?’ GETURL?QueryString POST : requested from form and large amount of information can be send to input streams. • POST is most preferred send large amount of data as data gets truncated in GET request. SERVLETSERVLET
  • 21. public class NewServlet extends HttpServlet { public void init(ServletConfig conf) {init code;} public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {Get Service code;} public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {Post Service code;} public void destroy() {destroy code;} } SERVLETSERVLET
  • 22. res.setContentType( “MIME TYPE”); To set the header format of response ServletOutputStream sos=res.getOutputStream(); To create OutputStream to send response sos.println( “html tags/data” ); Method used to send the data with OutputStream SERVLETSERVLET
  • 24. 1.Create a Servlet and save that as ServletName.java file. 2.Compile that from the place of creation. 3.Create a Deployment Descriptor with web.xml file, which includes servlet name and servlet mapping. 4.Deploy the class file and deployment descriptor into web server with the specified process of deployment of a web server. SERVLETSERVLET
  • 25. web.xmlweb.xml <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>ServletName</servlet-name> <servlet-class>ServletClassName</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletName</servlet-name> <url-pattern>/vfolder/ServletName</url-pattern> </servlet-mapping> </web-app>
  • 26. •The hierarchy structure to deploy the servlet file in tomcat web server. SERVLET DeploymentSERVLET Deployment
  • 27. •war file has to be created to deploy the web application into web server. •Creating “application.war” is possible by “jar” command SERVLET DeploymentSERVLET Deployment prompt> jar –cvf <war_filename> <info_folder> Example: C:erp:> jar –cvf erp.jar .WEB-INF
  • 28. Requesting from ClientRequesting from Client Call The servlet by using the URL in client application (HTML Form, Browser AddressBar, Applet etc.) as….. http://HostIpAddress:PortNo/app_name/url- pattern Example: http://localhost:8080/erp/register http://127.0.0.1:8080/erp/login
  • 29. Requesting from ClientRequesting from Client Call The servlet by using HTML Form <form action=“http://IpAddress:port/application/vFilena me” method=“post”> <button type=“submit”> </form>
  • 30. Requesting from ClientRequesting from Client Call The servlet by using Applet/Midlet String ues=URLEncoder.encode(“url”); URL u=new URL(ues); URLConnection con=u.openConnection(); BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()); String s=br.readLine(); ta.setText(s); //ta is TextArea
  • 31. Request ParametersRequest Parameters Enumeration e = req.getParameterNames() To get parameter names sent with the request String name = (String) e.getNextElement() To get name stored in Enumeration Object String[] s = req.getPrameter(String) To get the parameter value of given name String[] s = req.getPrameterValues(String) To get multiple parameter values of given name
  • 32. Request ParametersRequest Parameters String user = req.getPrameter(“user”) String pwd = req.getPrameter(“password”) Note: This will become hardcode of parameter names and no. of parameter. servlet may not work in case of any changes in parameter names/numbers in client request. Better to get all the names of parameters sent in request and then get the values of each parameter name.
  • 33. Request ParametersRequest Parameters Enumeration e = req.getParamenterNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = req.getParamenter(name); out.println(name + " = " + value); }
  • 34. Servlet ContainerServlet Container A servlet container comprises essentially the component of a web server that hosts and interacts with Java servlets. Web components (Servlet, JSP) run in a Web container which provides system services to Web components. Web container specifies a runtime environment for web components that includes security, life-cycle management, deployment, and other services.
  • 36. HTTPHTTP •Http is a stateless protocol. Every request is treated as request from a new user, even though the same client is requesting. •Http is stateless since the purpose of this protocol is just to distribute the information and not to retain information about client. •Each time a client retrieves a Web page, it opens a separate connection to the Web server, and the server does not automatically maintain contextual information about a client.
  • 37. Session TrackingSession Tracking •Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time. •To maintain the information of client, Cookie is invented by Netscape company. •Cookie is a part of Http.
  • 38. Session TrackingSession Tracking URL rewriting is used by appending a unique ID after the URL to identify the user. Hidden <form> fields can be used to store a unique ID for the session. Cookies are small files that the servlet can store on the client computer, and retrieve later. Http Session is an alternative to cookies. It keeps the session data available until browsing ends.
  • 39. URL Rewriting • Every local URL requested by user can be modified dynamically by the servlet to include extra info (session tracking info). • Extra info can hold information for the session, e.g. Session id, User Name etc. e.g. URL with an additional parameter added on by your code: – http://server/MyServlet?sessionid=123
  • 40. URL Rewriting Example: banking application. Bank employee’s branch-id is passed from one servlet to another to save re-entry // Get the current employee and branch ids String bid = req.getParameter(branchid); String eid = req.getParameter(empid); out.println(“<FORM ACTION = ”bankservlet? branchid=“+bid+”&empid=“+eid+"">"); out.println("</FORM>");
  • 41. Hidden Fields •“Hidden” fields are added to a form which will not be displayed on the browser <form action=“/moviefinder” method=“post”> <input type=“hidden” name=“pin” value=“420”> •From servlets, there is no difference in hidden fields and visible fields, both are request parameters only. •The servlet retrieves the hidden fields by using req.getParameter(“pin”) or req.getParameterValues(“pin”)
  • 42. Hidden Fields Example: String[] items = req.getParameterValues("item"); out.println("<FORM ACTION="someServlet" METHOD=POST>"); if (items != null) for (int i = 0; i < items.length; i++){ out.println("<INPUT TYPE=HIDDEN NAME="item“ VALUE=""+items[i]+"">"); } out.println("Would you like to<BR>"); out.println("<INPUT TYPE=SUBMIT VALUE="Add More Items">"); out.println("<INPUT TYPE=SUBMIT VALUE="Check Out">"); out.println("</FORM>");
  • 43. Cookies are name, valued objects which are created at server and stored on client side by the server. Cookie contents the information of client itself. The next time client sends the request, cookie is also send as part of request. Bye default Cookie is stored as text file in c:windowstemp CookieCookie
  • 44. Cookie Every cookie has only one name and value Cookie will be associated with Max Age, Domain Name, Path and Comment Limitations: •Max size of cookie can be 4KB •Max no. of cookies per site can be 20 •Not more than 300 cookies total
  • 45. Max Age: Default is up to destroying the browser. -ve means valid till current session. 0 means deleting cookie on client side. We can set the age of cookie explicitly as 24x60x60 for 1 day 2x24x60x60 for 2 days etc. CookieCookie
  • 46. Domain: Every cookie will have domain apart from maximum age. Default of cookie is the domain from which cookie is sent to the client. Path: Cookie having a path will not be send to server if request URL doesn't contain the cookie path. Comment: Some user agents have facility to worn the clients before accepting cookies. This working is through a dialog which can also show comment of the cookie. CookieCookie
  • 47. Cookie is a class present in javax.servlet.http package. Constructor: Cookie(String name, String value) res.addCookie(c); Cookie[ ] c = req.getCookies(); CookieCookie
  • 48. Methods: String n=c.getName() String v=c.getValue() Int t=c.getMaxAge() c.setMaxAge(int) String p=c.getPath() c.setPath(String) String com=c.getComment(), c.setComment(String) CookieCookie
  • 49. String n = req.getParameter(“pname"); String v = req.getParameter(“pvalue”); Cookie nc = new Cookie(n, v); res.addCookie(nc); Cookie[] old_cs = req.getCookies(); for(Cookie oc:old_cs) res.addCookie(oc); CookieCookie
  • 50. if(v.equals(“bill”) { Double tbill=0.0; Cookie[ ] pcs = req.getCookies(); for(Cookie c:pcs)tbill+=Double.valueOf(c.getValue()); Cookie tb=new Cookie(“tbill”, tbill.toString()); res.addCookie(tb); } CookieCookie
  • 51. Advantages: •Cookies can easily store more data than hidden fields •Data is stored on the client computer, not on server which saves space on the server and will not have any effect on server performance. Disadvantages: •Data is stored on the client computer, this means the data is neither safe nor secure •Cookies are good for keeping session data, not user data •Cookies may be discarded or the user may contact the server from another computer •Users can tell their browser to turn cookies off CookieCookie
  • 52. SessionSession A Session begins when a client establishes a connection with http server. For every client an object will be created at server side which is called as HttpSession. Session is a concept which internally works with cookie. It is called as Server Side Cookie. HttpSession stores the information of client on the server which is identified by the server by using cookie, which is created and set by the web server (Servlet Engine).
  • 53. Session will have the features of storing and retrieving the information. Cookie is validated till the session is valid. It is valid until the client is connected to server. Session may also disposed if the client is idle for more than a specific time, which is dependent on server vendor/ Administrator. Session object implements the interface of HttpSession. SessionSession
  • 54. SessionSession HttpSession ses = req.getSession(); Creates a new HttpSession object, or retrieves a previous one Creates a unique session ID Makes a new cookie object Associates the cookie with the session ID Puts the cookie in the response (under the Set-Cookie header)
  • 55. HttpSession ses = req.getSession(); Enumeration e = ses.getAttributeNames(); while (e.hasMoreElements()) { String n = (String)e.nextElement(); String v = ses.getAttribute(name).toString(); out.println(n + " = " + v); } SessionSession
  • 56. Methods: hs.removeAttribute(name); hs.invalidate(); Boolean b=hs.isNew(); String id=hs.getId(); long t=hs.getCreationTime(); long t=hs.getLastAccessedTime(); SessionSession
  • 57. Servlet to Servlet CommunicationServlet to Servlet Communication res.encodeRedirectURL(“URL?QueryString”)); Example: res.encodeRedirectURL(“http://server:8080/servlet/color ”)); res.encodeRedirectURL(“http://server:8080/color.html”)) ;
  • 58. All The Best …. I Career Craft