SlideShare a Scribd company logo
Servlets
Servlets
 Java Servlet is a java object file developed as a
component and runs on the server.
 Servlets are programs that run on a Web or application
server and act as a middle layer between a request coming
from a Web browser or other HTTP client and databases or
applications on the HTTP server
 Servlets is a component can be invoked from HTML.
Note:
 Servlets cannot run independently as a main application
like the java applet, the servlet does not have main method.
Servlets
 Servlet do not display a graphical interface to the user.
 A servlet’s work is done at the server and only the results
of the servlet’s processing are returned to the client in the
form of HTML.
 A Servlet is a Java technology-based Web component,
managed by a container that generates dynamic content.
 Like other Java technology-based components, Servlets
are platform-independent Java classes that are compiled
to platform-neutral byte code that can be loaded
dynamically into and run by a Java technology-enabled
Web server.
Predessor of servlet
 In the early days of the web u have to
use the Common Gateway
interface(CGI) to perform server side
processing of forms and interaction with
the datadase.
 Later microsoft ASP technology enable
server side processing using Vbscript,
Javascript.
Difference Between Servlet & CGI
 The advantages of using servlets are their fast
performance and ease of use combined with more power
over traditional CGI (Common Gateway Interface).
 Traditional CGI scripts written in Java have a number of
disadvantages when it comes to performance
 When an HTTP request is made, a new process is created
for each call of the CGI script. This overhead of process
creation can be very system-intensive, especially when the
script does relatively fast operations. Thus, process
creation will take more time than CGI script execution.
 Java servlets solve this, as a servlet is not a separate
process. Each request to be handled by a servlet is
handled by a separate Java thread within the Web server
process, omitting separate process forking (split) by the
HTTP domain.
Difference Between Servlet & CGI
 Simultaneous CGI request causes the CGI script to be
copied and loaded into memory as many times as there
are requests.
 However, with servlets, there are the same amount of
threads as requests, but there will only be one copy of the
servlet class created in memory that stays there also
between requests.
 A servlet can be run by a servlet engine in a restrictive
environment, called a sandbox. This is similar to an applet
that runs in the sandbox of the Web browser. This makes a
restrictive use of potentially harmful servlets possible.
Advantages of Servlets
 Platform Independence:
Servlets are written entirely in java so these are platform
independent.
Servlets can run on any Servlet enabled web server.
 Performance
 Due to interpreted nature of java, programs written in
java are slow.
 But the java Servlets runs very fast. These are due to
the way Servlets run on web server.
 For any program initialization takes significant amount
of time. But in case of Servlets initialization takes place
first time it receives a request and remains in memory till
times out or server shut downs.
 Extensibility
Java Servlets are developed in java which is robust, well-
designed and object oriented language which can be
extended or polymorphed into new objects.
So the java Servlets take all these advantages and can
be extended from existing class to provide the ideal
solutions.
 4. Safety Java provides very good safety features
like memory management, exception handling etc.
Servlets inherits all these features and emerged as
a very powerful web server extension.
 5. Secure Servlets are server side components, so it
inherits the security provided by the web server.
Servlets are also benefited with Java Security
Manager.
Life cycle of a servlet
• Init () Method
• Service () Method
• Destroy() method
Init () Method:-
 During initialization stage of the Servlet life cycle, the web
container initializes the servlet instance by calling the init()
method.
 The container passes an object implementing the ServletConfig
interface via the init() method.
 This configuration object allows the servlet to access name-
value initialization parameters from the web application.
• Service () Method:-
◦ After initialization, the servlet can service client requests. each request
is serviced in its own separate thread.
◦ The Web container calls the service() method of the servlet for every
request.
◦ The service() method determines the kind of request being made and
dispatches it to an appropriate method to handle the request.
◦ The developer of the servlet must provide an implementation for these
methods. If a request for a method that is not implemented by the
servlet is made, the method of the parent class is called, typically
resulting in an error being returned to the requester.
• Destroy() method:-
◦ Finally, the Web container calls the destroy() method that takes the
servlet out of service. The destroy() method, like init(), is called only
once in the lifecycle of a servlet.
Types of servlets
• Generic Servlets:
Generic Servlets are protocal independent that
is they do not contain any inherent support for any
protocal.
Generic Servlets handle request by overriding
the services() method.
• HTTP Servlets:
HTTP Servlets are HTTP protocal specific. This
makes it very useful in a browser environment.
In case of HTTP Servlets, service() method
route the request to another method based on which
HTTP transfer method is used.
Using Tomcat for Servlet Development
 To create servlets, you will need access
to a servlet development environment.
 Tomcat is an open-source product
maintained by the Jakarta Project of the
Apache Software Foundation.
 It contains the class libraries,
documentation, and runtime support that
you will need to create and test servlets.
Servlet API
 Two packages contain the classes and interfaces that are
required to build servlets.
 javax.servlet
 javax.servlet.http.
They constitute the Servlet API.
 These packages are not part of the Java core packages.
Instead, they are standard extensions provided by Tomcat.
 The Servlet API has been in a process of ongoing
development and enhancement. The current servlet
specification is version 2.4,
Simple Servlet program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
public class ServletTemplate extends HttpServlet {
Declaring a class Name of the class
Subclass the httpservlet
class to create a servlet
public void doGet(HttpServletRequest request,
HttpServletResponse response)
You are overriding the doget
method that comes from the
httpservlet class
The parameter is a
httpsevletrequest object that
you are naming request
The parameter is a
httpsevletresponse object that
you are naming response
throws ServletException, IOException
You are declaring that the doget
method can throw two exceptions
ServletException, IOException
Executing Servlet Program
Setting Class path
1. My computer->Properties->Advance->Environment
Variables->
Edit User Variable
Variable name: path
Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program
Filesservlet.jar;
Edit System Variable
Variable name: CLASSPATH
Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program
Filesservlet.jar;%.%;
2. Running the servlet in cmd prompt
C:Documents and Settingseec-cs>cd
C:>cd C:Program FilesApache Tomcat
4.0webappsexamplesWEB-INFclasses
C:Program FilesApache Tomcat
4.0webappsexamplesWEB-INFclasses>javac HelloW
orld.java
C:Program FilesApache Tomcat
4.0webappsexamplesWEB-INFclasses>
3. Start Tomcat
4. Open IE and type below link
 http://localhost:8080/examples/servlet/H
elloWorld
javax.servlet Package
 The javax.servlet package contains a number of
interfaces and classes that establish the framework in
which servlets operate.
 The following table summarizes the core interfaces
that are provided in this package.
 All servlets must implement this interface or extend a
class that implements the interface.
Reading Servlet Parameters
 The ServletRequest interface includes
methods that allow you to read the names and
values of parameters that are included in a
client request
javax.servlet.http package
Classes
HttpServletRequest Interface
 The HttpServletRequest interface enables a servlet to
obtain information about a client request.
HttpServletResponse Interface
The HttpServletResponse interface enables a servlet
to formulate an HTTP response to a client.
HttpSession Interface
 The HttpSession interface enables a servlet to read
and write the state information that is associated with
an HTTP session.
HttpSessionBindingListener Interface
 The HttpSessionBindingListener
interface is implemented by objects that
need to be notified when they are bound
to or unbound from an HTTP session.
Handling HTTP Requests and Responses
 Servlets can be used for handling both the GET Requests
and the POST Requests.
 The HttpServlet class is used for handling HTTP GET /
POST Requests as it has some specialized methods that
can efficiently handle the HTTP requests.
 These methods are:
◦ doGet( )
◦ doPost( )
◦ doPut( )
◦ doDelete( )
◦ doOptions( )
◦ doTrace( )
◦ doHead( )
 An individual developing Servlets for handling HTTP
Requests needs to override one of these methods in
order to process the request and generate a response.
The servlet is invoked dynamically when an end-user
submits a form.
 If Form method attribute value is GET, then doGet( )
method of servlet will be called, if method=”POST”
doPost( ) method of servlet which is mentioned as action
will be called.
 Ex: <form action=”sampleServlet” method=”GET”>
 In above example since method is GET, sampleServlet’s
doGet( ) will be called.
 Both doGet( ) and doPost( ) takes two arguments objects of
HttpServletRequest and HttpServletResponse classes.
 Ex: public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException
 public void doPost(HttpServletRequest req,HttpServletResponse
res) throws ServletException, IOException
 In above example req is an object of HttpServletRequest class
which contains the incoming information (information passed by
client program).
 The res is an object of HttpServletResponse class which
contains the outgoing information (response back to client).
Getting request data
 The request object of HttpServletRequest class contains the
incoming request data sent by client program.
 By using the following methods we can get the request parameter
values.
 Request parameters for the servlet are the strings sent by the
client to a servlet container as part of its request.
 The parameters are stored as a set of name-value pairs. Multiple
parameter values can exist for any given parameter name. The
following methods of the ServletRequest interface are available to
access parameters:
◦ getParameter ( )
◦ getParameterNames ( )
◦ getParameterValues ( )
 getParameter ( ) method is used to access single
value, takes name of input parameter as an argument
and returns a string object.
Ex: String s=req.getParameter(“user”);
 getParameterValues ( ) method is used to access
multiple value entered by user in a client program, it
takes name of input parameter as an argument and
returns a array of string object.
 Ex: String [ ] lang=req.getParameterValues
(“language”);
When we want to access all the parameters of a form, we make
use of Enumeration object and its methods as shown below.
Ex: Enumeration en;
String pname;
String pvalue;
en = request.getParameterNames();
while (en.hasMoreElements())
{
pname = (String) en.nextElement();
pvalue= request.getParameterValues(pname);
for(int i=0;i<pvalue.length;i++)
{
out.println(pvalue[i]);
}
}
Cookies
 Cookies are small bits of textual information that a Web
server sends to a browser and that the browser returns
unchanged when visiting the same Web site or domain
later.
 To send cookies to the client, a servlet would create one or
more cookies with the appropriate names and values via
new Cookie(name, value).
 A Cookie is created by calling the Cookie constructor, which
takes two strings: the cookie name and the cookie value.
Neither the name nor the value should contain whitespace
or any of: [ ] ( ) = , " / ? @ : ;
 Ex: Cookie userCookie = new Cookie("user", "uid1234");
 The cookie is added to the Set-Cookie response
header by means of the addCookie method of
HttpServletResponse.
 Cookie userCookie = new Cookie("user", "uid1234");
 response.addCookie(userCookie);
The getXXX( ) method can be used to retrieve the attribute XXX of a cookie
object, which returns the string value. For example getName( ) used to
retrieve the name of a cookie.
The setXXX( ) method is used to set the value of XXX attribute of a cookie,
which accepts the value as argument which need to be set.
Ex: c.setValue(“123”); It sets Value attribute of cookie c as 123.
Servlet-Sessions
 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 e-commerce.
 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?
 Servlets provide an outstanding
technical solution: the HttpSession API.
 “A session is created each time a client
requests service from a Java servlet.
The servlet processes the request and
responds accordingly, after which the
session is terminated.”
JSP - Java Server Pages
Introduction
 JSP is one of the most powerful, easy-to-use,
and fundamental tools in a Web-site developer's
toolbox.
 JSP combines HTML and XML with Java servlet
(server application extension) and JavaBeans
technologies to create a highly productive
environment for developing and deploying
reliable, interactive, high-performance platform-
independent Web sites.
 JSP facilitates the creation of dynamic content
on the server.
 It is part of the Java platform's integrated
solution for server-side programming, which
provides a portable alternative to other server-
side technologies, such as CGI.
 JSP integrates numerous Java application
technologies, such as Java servlet, JavaBeans,
JDBC, and Enterprise JavaBeans.
 It also separates information presentation from
application logic and fosters a reusable
component model of programming.
Advantages of JSP over Servlets
 Servlet use println statements for printing an HTML
document which is usually very difficult to use. JSP has no
such tedious task to maintain.
 JSP needs no compilation, CLASSPATH setting and
packaging.
 In a JSP page visual content and logic are seperated,
which is not possible in a servlet.
 There is automatic deployment of a JSP; recompilation is
done automatically when changes are made to JSP pages.
 Usually with JSP, Java Beans and custom tags web
application is simplified.
Fundamental JSP Tags
 JSP tags are an important syntax element of Java Server
Pages which start with "<%" and end with "%>" just like
HTML tags. JSP tags normally have a "start tag", a "tag
body" and an "end tag". JSP tags can either be predefined
tags or loaded from an external tag library.
 Fundamental tags used in Java Server Pages are classified
into the following categories:-
 Declaration tag
 Expression tag
 Directive tag
 Scriptlet tag
 Comments
Declaration tag
 The declaration tag is used within a Java Server page to
declare a variable or method that can be referenced by
other declarations, scriptlets, or expressions in a java
server page.
 A declaration tag does not generate any output on its own
and is usually used in association with Expression or
Scriplet Tags.
 Declaration tag starts with "<%!" and ends with "%>"
surrounding the declaration.
Syntax :- <%! Declaration %>
Example: <%! int var = 1; %>
<%! int x, y ; %>
Expression tag
 An expression tag is used within a Java
Server page to evaluate a java expression
at request time.
 The expression enclosed between "<%="
and "%>" tag elements is first converted
into a string and sent inline to the output
stream of the response.
Syntax :- <%= expression %>
Example: <%= new java.util.Date() %>
Directive tag
 Directive tag is used within a Java Server
page to specify directives to the application
server .
 The directives are special messages which
may use name-value pair attributes in the
form attr="value".
Syntax :- <%@directive attribute="value" %>
Where directive may be:
1. page: page is used to provide the information about it.
Example: <%@page language="java" %>
2. include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %>
3. taglib: taglib is used to use the custom tags in the JSP
pages (custom tags allows us to defined our own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag"
%>
Scriptlet tag
 A Scriptlet tag is used within a Java Server
page to execute a java source code scriplet
which is enclosed between "<%" and "%>" tag
elements.
 The output of the java source code scriplet
specified within the Scriptlet tag is executed at
the server end and is inserted in sequence with
rest of the web document for the client to
access through web browser.
Syntax :- <% java code %>
Comments
 Comments tag is used within a Java Server
page for documentation of Java server page
code.
 Comments surrounded with "<%/*" and "*/%"
tag elements are not processed by JSP engine
and therefore do not appear on the client side
web document but can be viewed through the
web browser’s "view source" option.
 Syntax :- <%-- comment -- %>
Request String
 The browser generates a user request string whenever the
submit is selected.
 The User request string consists of the URL and the query
string.
http://localhost:8080/examples/test/reg.jsp?fname=“bob”&lna
me=“smith”
 The getParameter(name) is the method used to parse a
value of a specified field.
<% string firstname = request.getParameter(fname)
string lastname = request.getParameter(lname)
%>
User Sessions
 A JSP program must be able to track a
session as a client moves between HTML
pages and JSP programs.
There are three commonly used methods to
track a session.
1. Using Hidden Field
2. Using Cookies
3. Using JavaBean
Cookies
 Cookies is a small piece of information created by a JSP program that is
stored on the Client’s hard disk by the browser.
 You can create and read a cookie by using methods of the cookie class
and the response object.
Example: how to create a cookie
<HTML>
<HEAD>
<TITLE>JSP PROGRAMMING </TITLE>
</HEAD>
<BODY>
<%! String MyCookieName = “userId”;
String MyCookieValue = “Jk12345”;
Response.addCookie(new Cookie(MyCookieName, MyCookieValue));
%>
</BODY>
</HTML>
HOW TO READ A COOKIE
<HTML>
<HEAD>
<TITLE> JSP Programming</TITLE>
</HEAD>
<BODY>
<%! String MyCookieName=“userID”;
String MyCookieValue;
String Cname,Cvalue;
int found=0;
Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++){
CName=cookies[i].getName();
CValue= cookie[i].getValue();
if(MyCookieName.equals(cookieNames[i])){
found=1;
MyCookieValue=CookieValue;
}
}
if(found==1){ %>
<p> Cookie name =<% MYCookieName%></p>
<p> Cookie Value=<% MyCookieValue %></p>
<&}>
</BODY>
</HTML>
Session Objects
 A JSP database system is able to share
information among JSP programs within
a session by using a session object.
 Each time a session is created, a unique
ID is assigned to the session and stored
as a cookie

More Related Content

What's hot

Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
Payal Dungarwal
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
Halil Burak Cetinkaya
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
Pihu Goel
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
Elizabeth alexander
 
Applets
AppletsApplets
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
rajshreemuthiah
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Kasun Madusanke
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
sandeep54552
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
VMahesh5
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
amitksaha
 

What's hot (20)

JDBC
JDBCJDBC
JDBC
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Applets
AppletsApplets
Applets
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Servlet
Servlet Servlet
Servlet
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
 

Viewers also liked

Ch 2 lattice & boolean algebra
Ch 2 lattice & boolean algebraCh 2 lattice & boolean algebra
Ch 2 lattice & boolean algebra
Rupali Rana
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in java
Acp Jamod
 
Tutorial su JMS (Java Message Service)
Tutorial su JMS (Java Message Service)Tutorial su JMS (Java Message Service)
Tutorial su JMS (Java Message Service)
Federico Paparoni
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
Paul Pajo
 
Java Mail
Java MailJava Mail
JMS - Java Messaging Service
JMS - Java Messaging ServiceJMS - Java Messaging Service
JMS - Java Messaging Service
Peter R. Egli
 

Viewers also liked (8)

EJB .
EJB .EJB .
EJB .
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 
Ch 2 lattice & boolean algebra
Ch 2 lattice & boolean algebraCh 2 lattice & boolean algebra
Ch 2 lattice & boolean algebra
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in java
 
Tutorial su JMS (Java Message Service)
Tutorial su JMS (Java Message Service)Tutorial su JMS (Java Message Service)
Tutorial su JMS (Java Message Service)
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Java Mail
Java MailJava Mail
Java Mail
 
JMS - Java Messaging Service
JMS - Java Messaging ServiceJMS - Java Messaging Service
JMS - Java Messaging Service
 

Similar to Chapter 3 servlet & jsp

Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
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
PRIYADARSINISK
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
karthiksmart21
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
sindhu991994
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and ServletsRaghu nath
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
Auwal Amshi
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
ADEEBANADEEM
 
J servlets
J servletsJ servlets
J servlets
reddivarihareesh
 
Java servlets
Java servletsJava servlets
Java servlets
Mukesh Tekwani
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
Servlets
ServletsServlets
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
Prabu U
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
Senthil Kumar
 

Similar to Chapter 3 servlet & jsp (20)

Java Servlet
Java ServletJava Servlet
Java Servlet
 
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
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
J servlets
J servletsJ servlets
J servlets
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets
ServletsServlets
Servlets
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Weblogic
WeblogicWeblogic
Weblogic
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 

More from Jafar Nesargi

Network adpater,cabel,cards ,types, network devices
Network adpater,cabel,cards ,types, network devicesNetwork adpater,cabel,cards ,types, network devices
Network adpater,cabel,cards ,types, network devices
Jafar Nesargi
 
An introduction to networking
An introduction to networkingAn introduction to networking
An introduction to networking
Jafar Nesargi
 
Computer basics Intro
Computer basics IntroComputer basics Intro
Computer basics Intro
Jafar Nesargi
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database languageJafar Nesargi
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relationalJafar Nesargi
 
Chapter 4 record storage and primary file organization
Chapter 4 record storage and primary file organizationChapter 4 record storage and primary file organization
Chapter 4 record storage and primary file organizationJafar Nesargi
 
Introduction to-oracle
Introduction to-oracleIntroduction to-oracle
Introduction to-oracleJafar Nesargi
 
Cascading style sheets
Cascading style sheetsCascading style sheets
Cascading style sheetsJafar Nesargi
 
Session1 gateway to web page development
Session1   gateway to web page developmentSession1   gateway to web page development
Session1 gateway to web page developmentJafar Nesargi
 
Record storage and primary file organization
Record storage and primary file organizationRecord storage and primary file organization
Record storage and primary file organizationJafar Nesargi
 
Introduction to-oracle
Introduction to-oracleIntroduction to-oracle
Introduction to-oracleJafar Nesargi
 

More from Jafar Nesargi (20)

Network adpater,cabel,cards ,types, network devices
Network adpater,cabel,cards ,types, network devicesNetwork adpater,cabel,cards ,types, network devices
Network adpater,cabel,cards ,types, network devices
 
An introduction to networking
An introduction to networkingAn introduction to networking
An introduction to networking
 
Computer basics Intro
Computer basics IntroComputer basics Intro
Computer basics Intro
 
Css
CssCss
Css
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database language
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relational
 
Chapter 4 record storage and primary file organization
Chapter 4 record storage and primary file organizationChapter 4 record storage and primary file organization
Chapter 4 record storage and primary file organization
 
Chapter3
Chapter3Chapter3
Chapter3
 
Introduction to-oracle
Introduction to-oracleIntroduction to-oracle
Introduction to-oracle
 
Chapter2
Chapter2Chapter2
Chapter2
 
Cascading style sheets
Cascading style sheetsCascading style sheets
Cascading style sheets
 
Session1 gateway to web page development
Session1   gateway to web page developmentSession1   gateway to web page development
Session1 gateway to web page development
 
Introduction to jsp
Introduction to jspIntroduction to jsp
Introduction to jsp
 
Rmi
RmiRmi
Rmi
 
Java bean
Java beanJava bean
Java bean
 
Networking
NetworkingNetworking
Networking
 
Chapter2 j2ee
Chapter2 j2eeChapter2 j2ee
Chapter2 j2ee
 
Chapter 1 swings
Chapter 1 swingsChapter 1 swings
Chapter 1 swings
 
Record storage and primary file organization
Record storage and primary file organizationRecord storage and primary file organization
Record storage and primary file organization
 
Introduction to-oracle
Introduction to-oracleIntroduction to-oracle
Introduction to-oracle
 

Recently uploaded

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 

Recently uploaded (20)

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 

Chapter 3 servlet & jsp

  • 2. Servlets  Java Servlet is a java object file developed as a component and runs on the server.  Servlets are programs that run on a Web or application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server  Servlets is a component can be invoked from HTML. Note:  Servlets cannot run independently as a main application like the java applet, the servlet does not have main method.
  • 3. Servlets  Servlet do not display a graphical interface to the user.  A servlet’s work is done at the server and only the results of the servlet’s processing are returned to the client in the form of HTML.  A Servlet is a Java technology-based Web component, managed by a container that generates dynamic content.  Like other Java technology-based components, Servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
  • 4. Predessor of servlet  In the early days of the web u have to use the Common Gateway interface(CGI) to perform server side processing of forms and interaction with the datadase.  Later microsoft ASP technology enable server side processing using Vbscript, Javascript.
  • 5. Difference Between Servlet & CGI  The advantages of using servlets are their fast performance and ease of use combined with more power over traditional CGI (Common Gateway Interface).  Traditional CGI scripts written in Java have a number of disadvantages when it comes to performance  When an HTTP request is made, a new process is created for each call of the CGI script. This overhead of process creation can be very system-intensive, especially when the script does relatively fast operations. Thus, process creation will take more time than CGI script execution.  Java servlets solve this, as a servlet is not a separate process. Each request to be handled by a servlet is handled by a separate Java thread within the Web server process, omitting separate process forking (split) by the HTTP domain.
  • 6. Difference Between Servlet & CGI  Simultaneous CGI request causes the CGI script to be copied and loaded into memory as many times as there are requests.  However, with servlets, there are the same amount of threads as requests, but there will only be one copy of the servlet class created in memory that stays there also between requests.  A servlet can be run by a servlet engine in a restrictive environment, called a sandbox. This is similar to an applet that runs in the sandbox of the Web browser. This makes a restrictive use of potentially harmful servlets possible.
  • 7. Advantages of Servlets  Platform Independence: Servlets are written entirely in java so these are platform independent. Servlets can run on any Servlet enabled web server.  Performance  Due to interpreted nature of java, programs written in java are slow.  But the java Servlets runs very fast. These are due to the way Servlets run on web server.  For any program initialization takes significant amount of time. But in case of Servlets initialization takes place first time it receives a request and remains in memory till times out or server shut downs.
  • 8.  Extensibility Java Servlets are developed in java which is robust, well- designed and object oriented language which can be extended or polymorphed into new objects. So the java Servlets take all these advantages and can be extended from existing class to provide the ideal solutions.  4. Safety Java provides very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.  5. Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.
  • 9. Life cycle of a servlet • Init () Method • Service () Method • Destroy() method Init () Method:-  During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method.  The container passes an object implementing the ServletConfig interface via the init() method.  This configuration object allows the servlet to access name- value initialization parameters from the web application.
  • 10. • Service () Method:- ◦ After initialization, the servlet can service client requests. each request is serviced in its own separate thread. ◦ The Web container calls the service() method of the servlet for every request. ◦ The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. ◦ The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester. • Destroy() method:- ◦ Finally, the Web container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet.
  • 11.
  • 12. Types of servlets • Generic Servlets: Generic Servlets are protocal independent that is they do not contain any inherent support for any protocal. Generic Servlets handle request by overriding the services() method. • HTTP Servlets: HTTP Servlets are HTTP protocal specific. This makes it very useful in a browser environment. In case of HTTP Servlets, service() method route the request to another method based on which HTTP transfer method is used.
  • 13. Using Tomcat for Servlet Development  To create servlets, you will need access to a servlet development environment.  Tomcat is an open-source product maintained by the Jakarta Project of the Apache Software Foundation.  It contains the class libraries, documentation, and runtime support that you will need to create and test servlets.
  • 14. Servlet API  Two packages contain the classes and interfaces that are required to build servlets.  javax.servlet  javax.servlet.http. They constitute the Servlet API.  These packages are not part of the Java core packages. Instead, they are standard extensions provided by Tomcat.  The Servlet API has been in a process of ongoing development and enhancement. The current servlet specification is version 2.4,
  • 15. Simple Servlet program import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } }
  • 16. public class ServletTemplate extends HttpServlet { Declaring a class Name of the class Subclass the httpservlet class to create a servlet
  • 17. public void doGet(HttpServletRequest request, HttpServletResponse response) You are overriding the doget method that comes from the httpservlet class The parameter is a httpsevletrequest object that you are naming request The parameter is a httpsevletresponse object that you are naming response
  • 18. throws ServletException, IOException You are declaring that the doget method can throw two exceptions ServletException, IOException
  • 19. Executing Servlet Program Setting Class path 1. My computer->Properties->Advance->Environment Variables-> Edit User Variable Variable name: path Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program Filesservlet.jar; Edit System Variable Variable name: CLASSPATH Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program Filesservlet.jar;%.%;
  • 20. 2. Running the servlet in cmd prompt C:Documents and Settingseec-cs>cd C:>cd C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses>javac HelloW orld.java C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses>
  • 21. 3. Start Tomcat 4. Open IE and type below link  http://localhost:8080/examples/servlet/H elloWorld
  • 22. javax.servlet Package  The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.  The following table summarizes the core interfaces that are provided in this package.  All servlets must implement this interface or extend a class that implements the interface.
  • 23. Reading Servlet Parameters  The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a client request
  • 25. HttpServletRequest Interface  The HttpServletRequest interface enables a servlet to obtain information about a client request.
  • 26. HttpServletResponse Interface The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
  • 27. HttpSession Interface  The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session.
  • 28. HttpSessionBindingListener Interface  The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session.
  • 29. Handling HTTP Requests and Responses  Servlets can be used for handling both the GET Requests and the POST Requests.  The HttpServlet class is used for handling HTTP GET / POST Requests as it has some specialized methods that can efficiently handle the HTTP requests.  These methods are: ◦ doGet( ) ◦ doPost( ) ◦ doPut( ) ◦ doDelete( ) ◦ doOptions( ) ◦ doTrace( ) ◦ doHead( )
  • 30.  An individual developing Servlets for handling HTTP Requests needs to override one of these methods in order to process the request and generate a response. The servlet is invoked dynamically when an end-user submits a form.  If Form method attribute value is GET, then doGet( ) method of servlet will be called, if method=”POST” doPost( ) method of servlet which is mentioned as action will be called.  Ex: <form action=”sampleServlet” method=”GET”>  In above example since method is GET, sampleServlet’s doGet( ) will be called.
  • 31.  Both doGet( ) and doPost( ) takes two arguments objects of HttpServletRequest and HttpServletResponse classes.  Ex: public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException  public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException  In above example req is an object of HttpServletRequest class which contains the incoming information (information passed by client program).  The res is an object of HttpServletResponse class which contains the outgoing information (response back to client).
  • 32. Getting request data  The request object of HttpServletRequest class contains the incoming request data sent by client program.  By using the following methods we can get the request parameter values.  Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request.  The parameters are stored as a set of name-value pairs. Multiple parameter values can exist for any given parameter name. The following methods of the ServletRequest interface are available to access parameters: ◦ getParameter ( ) ◦ getParameterNames ( ) ◦ getParameterValues ( )
  • 33.  getParameter ( ) method is used to access single value, takes name of input parameter as an argument and returns a string object. Ex: String s=req.getParameter(“user”);  getParameterValues ( ) method is used to access multiple value entered by user in a client program, it takes name of input parameter as an argument and returns a array of string object.  Ex: String [ ] lang=req.getParameterValues (“language”);
  • 34. When we want to access all the parameters of a form, we make use of Enumeration object and its methods as shown below. Ex: Enumeration en; String pname; String pvalue; en = request.getParameterNames(); while (en.hasMoreElements()) { pname = (String) en.nextElement(); pvalue= request.getParameterValues(pname); for(int i=0;i<pvalue.length;i++) { out.println(pvalue[i]); } }
  • 35. Cookies  Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting the same Web site or domain later.  To send cookies to the client, a servlet would create one or more cookies with the appropriate names and values via new Cookie(name, value).  A Cookie is created by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain whitespace or any of: [ ] ( ) = , " / ? @ : ;  Ex: Cookie userCookie = new Cookie("user", "uid1234");
  • 36.  The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse.  Cookie userCookie = new Cookie("user", "uid1234");  response.addCookie(userCookie);
  • 37. The getXXX( ) method can be used to retrieve the attribute XXX of a cookie object, which returns the string value. For example getName( ) used to retrieve the name of a cookie. The setXXX( ) method is used to set the value of XXX attribute of a cookie, which accepts the value as argument which need to be set. Ex: c.setValue(“123”); It sets Value attribute of cookie c as 123.
  • 38. Servlet-Sessions  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 e-commerce.  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?
  • 39.  Servlets provide an outstanding technical solution: the HttpSession API.  “A session is created each time a client requests service from a Java servlet. The servlet processes the request and responds accordingly, after which the session is terminated.”
  • 40. JSP - Java Server Pages Introduction  JSP is one of the most powerful, easy-to-use, and fundamental tools in a Web-site developer's toolbox.  JSP combines HTML and XML with Java servlet (server application extension) and JavaBeans technologies to create a highly productive environment for developing and deploying reliable, interactive, high-performance platform- independent Web sites.  JSP facilitates the creation of dynamic content on the server.
  • 41.  It is part of the Java platform's integrated solution for server-side programming, which provides a portable alternative to other server- side technologies, such as CGI.  JSP integrates numerous Java application technologies, such as Java servlet, JavaBeans, JDBC, and Enterprise JavaBeans.  It also separates information presentation from application logic and fosters a reusable component model of programming.
  • 42. Advantages of JSP over Servlets  Servlet use println statements for printing an HTML document which is usually very difficult to use. JSP has no such tedious task to maintain.  JSP needs no compilation, CLASSPATH setting and packaging.  In a JSP page visual content and logic are seperated, which is not possible in a servlet.  There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages.  Usually with JSP, Java Beans and custom tags web application is simplified.
  • 43. Fundamental JSP Tags  JSP tags are an important syntax element of Java Server Pages which start with "<%" and end with "%>" just like HTML tags. JSP tags normally have a "start tag", a "tag body" and an "end tag". JSP tags can either be predefined tags or loaded from an external tag library.  Fundamental tags used in Java Server Pages are classified into the following categories:-  Declaration tag  Expression tag  Directive tag  Scriptlet tag  Comments
  • 44. Declaration tag  The declaration tag is used within a Java Server page to declare a variable or method that can be referenced by other declarations, scriptlets, or expressions in a java server page.  A declaration tag does not generate any output on its own and is usually used in association with Expression or Scriplet Tags.  Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration. Syntax :- <%! Declaration %> Example: <%! int var = 1; %> <%! int x, y ; %>
  • 45. Expression tag  An expression tag is used within a Java Server page to evaluate a java expression at request time.  The expression enclosed between "<%=" and "%>" tag elements is first converted into a string and sent inline to the output stream of the response. Syntax :- <%= expression %> Example: <%= new java.util.Date() %>
  • 46. Directive tag  Directive tag is used within a Java Server page to specify directives to the application server .  The directives are special messages which may use name-value pair attributes in the form attr="value". Syntax :- <%@directive attribute="value" %>
  • 47. Where directive may be: 1. page: page is used to provide the information about it. Example: <%@page language="java" %> 2. include: include is used to include a file in the JSP page. Example: <%@ include file="/header.jsp" %> 3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags). Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
  • 48. Scriptlet tag  A Scriptlet tag is used within a Java Server page to execute a java source code scriplet which is enclosed between "<%" and "%>" tag elements.  The output of the java source code scriplet specified within the Scriptlet tag is executed at the server end and is inserted in sequence with rest of the web document for the client to access through web browser. Syntax :- <% java code %>
  • 49. Comments  Comments tag is used within a Java Server page for documentation of Java server page code.  Comments surrounded with "<%/*" and "*/%" tag elements are not processed by JSP engine and therefore do not appear on the client side web document but can be viewed through the web browser’s "view source" option.  Syntax :- <%-- comment -- %>
  • 50. Request String  The browser generates a user request string whenever the submit is selected.  The User request string consists of the URL and the query string. http://localhost:8080/examples/test/reg.jsp?fname=“bob”&lna me=“smith”  The getParameter(name) is the method used to parse a value of a specified field. <% string firstname = request.getParameter(fname) string lastname = request.getParameter(lname) %>
  • 51. User Sessions  A JSP program must be able to track a session as a client moves between HTML pages and JSP programs. There are three commonly used methods to track a session. 1. Using Hidden Field 2. Using Cookies 3. Using JavaBean
  • 52. Cookies  Cookies is a small piece of information created by a JSP program that is stored on the Client’s hard disk by the browser.  You can create and read a cookie by using methods of the cookie class and the response object. Example: how to create a cookie <HTML> <HEAD> <TITLE>JSP PROGRAMMING </TITLE> </HEAD> <BODY> <%! String MyCookieName = “userId”; String MyCookieValue = “Jk12345”; Response.addCookie(new Cookie(MyCookieName, MyCookieValue)); %> </BODY> </HTML>
  • 53. HOW TO READ A COOKIE <HTML> <HEAD> <TITLE> JSP Programming</TITLE> </HEAD> <BODY> <%! String MyCookieName=“userID”; String MyCookieValue; String Cname,Cvalue; int found=0; Cookie[] cookies=request.getCookies(); for(int i=0;i<cookies.length;i++){ CName=cookies[i].getName(); CValue= cookie[i].getValue(); if(MyCookieName.equals(cookieNames[i])){ found=1; MyCookieValue=CookieValue; } } if(found==1){ %> <p> Cookie name =<% MYCookieName%></p> <p> Cookie Value=<% MyCookieValue %></p> <&}> </BODY> </HTML>
  • 54. Session Objects  A JSP database system is able to share information among JSP programs within a session by using a session object.  Each time a session is created, a unique ID is assigned to the session and stored as a cookie