SlideShare a Scribd company logo
1 of 31
Servlet Fudamentals
Celsina Bignoli
bignolic@smccd.net
What can you build with Servlets?
• Search Engines
• E-Commerce Applications
• Shopping Carts
• Product Catalogs
• Intranet Applications
• Groupware Applications:
– bulletin boards
– file sharing
Servlets vs. CGI
• A Servlet does not run in a
separate process.
• A Servlet stays in memory
between requests.
• A CGI program needs to be
loaded and started for each
CGI request.
• There is only a single
instance of a servlet which
answers all requests
concurrently.
Browser 1
Web
Server
Browser 2
Browser N
Perl 1
Perl 2
Perl N
Browser 1
Web
Server
Browser 2
Browser N
Servlet
• Performance
– The performance of servlets is superior to CGI because there is
no process creation for each client request.
– Each request is handled by the servlet container process.
– After a servlet has completed processing a request, it stays
resident in memory, waiting for another request.
• Portability
– Like other Java technologies, servlet applications are portable.
• Rapid development cycle
– As a Java technology, servlets have access to the rich Java
library that will help speed up the development process.
• Robustness
– Servlets are managed by the Java Virtual Machine.
– Don't need to worry about memory leak or garbage collection,
which helps you write robust applications.
• Widespread acceptance
– Java is a widely accepted technology.
Benefits of Java Servlets
• A servlet is a Java class that can be loaded dynamically
into and run by a special web server.
• This servlet-aware web server, is known as servlet
container.
• Servlets interact with clients via a request-response
model based on HTTP.
• Therefore, a servlet container must support HTTP as the
protocol for client requests and server responses.
• A servlet container also can support similar protocols
such as HTTPS (HTTP over SSL) for secure
transactions.
Definitions
Browser HTTP
Server
Static
Content
Servlet
Container
HTTP Request
HTTP Response
Servlet
Servlet Container Architecture
Receive
Request
is servlet
loaded?
is servlet
current?
Send
Response
Process Request
Load Servlet
Yes
Yes
No
No
How Servlets Work
Servlet APIs
• Every servlet must implement
javax.servlet.Servlet interface
• Most servlets implement the interface by
extending one of these classes
–javax.servlet.GenericServlet
–javax.servlet.http.HttpServlet
Generic Servlet & HTTP Servlet
GenericServletGenericServlet
service ( )Server
ClientClient
HTTPServletHTTPServlet
service ( )HTTP
Server
BrowserBrowser
request
response
doGet( )
doPost( )
request
response
Interface javax.servlet.Servlet
• The Servlet interface defines methods
– to initialize a servlet
– to receive and respond to client requests
– to destroy a servlet and its resources
– to get any startup information
– to return basic information about itself, such as its
author, version and copyright.
• Developers need to directly implement this
interface only if their servlets cannot (or choose
not to) inherit from GenericServlet or
HttpServlet.
Life
Cycle
Methods
• void init(ServletConfig config)
– Initializes the servlet.
• void service(ServletRequest req, ServletResponse res)
– Carries out a single request from the client.
• void destroy()
– Cleans up whatever resources are being held (e.g., memory, file
handles, threads) and makes sure that any persistent state is
synchronized with the servlet's current in-memory state.
• ServletConfig getServletConfig()
– Returns a servlet config object, which contains any initialization
parameters and startup configuration for this servlet.
• String getServletInfo()
– Returns a string containing information about the servlet, such
as its author, version, and copyright.
GenericServlet - Methods
Initialization
init()
Service
service()
doGet()
doPost()
doDelete()
doHead()
doTrace()
doOptions()
Destruction
destroy()
Concurrent
Threads
of Execution
Servlet Life Cycle
HttpServlet - Methods
• void doGet (HttpServletRequest request,
HttpServletResponse response)
–handles GET requests
• void doPost (HttpServletRequest request,
HttpServletResponse response)
–handles POST requests
• void doPut (HttpServletRequest request,
HttpServletResponse response)
–handles PUT requests
• void doDelete (HttpServletRequest request,
HttpServletResponse response)
– handles DELETE requests
Servlet Request Objects
• provides client request information to a servlet.
• the servlet container creates a servlet request object and
passes it as an argument to the servlet's service
method.
• the ServletRequest interface define methods to retrieve
data sent as client request:
–parameter name and values
– attributes
– input stream
• HTTPServletRequest extends the ServletRequest
interface to provide request information for HTTP
servlets
HttpServletRequest - Methods
Enumeration getParameterNames()
an Enumeration of String objects, each String
containing the name of a request parameter; or an
empty Enumeration if the request has no
parameters
java.lang.String[] getParameterValues (java.lang.String name)
Returns an array of String objects containing all of
the values the given request parameter has, or
null if the parameter does not exist.
java.lang.String getParameter (java.lang.String name)
Returns the value of a request parameter as a
String, or null if the parameter does not exist.
HttpServletRequest - Methods
Cookie[] getCookies()
Returns an array containing all of the Cookie objects
the client sent with this request.
java.lang.String getMethod()
Returns the name of the HTTP method with whichthi
request was made, for example, GET, POST, or
PUT.
java.lang.String getQueryString()
Returns the query string that is contained in the
request URL after the path.
HttpSession getSession()
Returns the current session associated with this
request, or if the request does not have a session,
creates one.
Servlet Response Objects
• Defines an object to assist a servlet in
sending a response to the client.
• The servlet container creates a
ServletResponse object and passes it as
an argument to the servlet's service
method.
HttpServletResponse - Methods
java.io.PrintWriter getWriter()
Returns a PrintWriter object that can send
character text to the client
void setContentType (java.lang.String type)
Sets the content type of the response being sent
to the client. The content type may include the
type of character encoding used, for example,
text/html; charset=ISO-8859-4
int getBufferSize()
Returns the actual buffer size used for the
response
• Create a directory structure under Tomcat
for your application.
• Write the servlet source code.
• Compile your source code.
• deploy the servlet
• Run Tomcat
• Call your servlet from a web browser
Steps to Running a Servlet
• The webapps directory is the Tomcat installation dir
(CATALINA_HOME) is where you store your web applications.
• A web application is a collection of servlets and other contents
installed under a specific subset of the server's URL namespace.
• A separate directory is dedicated for each servlet application.
• Create a directory called myApp under the webapps directory.
• Create the src and WEB-INF directories under myApp, and create a
directory named classes under WEB-INF.
– The src directory is for your source files, and the classes directory under
WEB-INF is for your Java classes.
– If you have html files, you put them directly in the myApp directory.
• The admin, ROOT, and examples directories are for applications
created automatically when you install Tomcat
Create a Directory Structure
• Servlets implement the javax.servlet.Servlet interface.
• Because most servlets extend web servers that use the
HTTP protocol to interact with clients, the most common
way to develop servlets is by specializing the
javax.servlet.http.HttpServlet class.
• The HttpServlet class implements the Servlet interface
by extending the GenericServlet base class, and
provides a framework for handling the HTTP protocol.
• Its service() method supports standard HTTP requests
by dispatching each request to a method designed to
handle it.
• In myApp/src, create a file called TestingServlet.java
Write the Servlet Code
Servlet Example
1: import java.io.*;
2: import javax.servlet.*;
3: import javax.servlet.http.*;
4:
5: public class MyServlet extends HttpServlet
6: {
7: protected void doGet(HttpServletRequest req,
8: HttpServletResponse res)
9: {
10: res.setContentType("text/html");
11: PrintWriter out = res.getWriter();
12: out.println( "<HTML><HEAD><TITLE> Hello You!” +
13: “</Title></HEAD>” +
14: “<Body> HelloYou!!!</BODY></HTML>“ );
14: out.close();
16: }
17: }
An Example of Servlet (I)
Lines 1 to 3 import some packages which
contain many classes which are used by
the Servlet (almost every Servlet needs
classes from these packages).
The Servlet class is declared in line 5. Our
Servlet extends javax.servlet.http.HttpServlet,
the standard base class for HTTP Servlets.
In lines 7 through 16 HttpServlet's doGet
method is getting overridden
An Example of Servlet (II)
In line 12 we request a PrintWriter object to
write text to the response message.
In line 11 we use a method of the
HttpServletResponse object to set the content
type of the response that we are going to
send. All response headers must be set
before a PrintWriter or ServletOutputStream is
requested to write body data to the
response.
In lines 13 and 14 we use the PrintWriter to
write the text of type text/html (as specified
through the content type).
An Example of Servlet (III)
The PrintWriter gets closed in line 15 when
we are finished writing to it.
In lines 18 through 21 we override the
getServletInfo() method which is supposed to
return information about the Servlet, e.g.
the Servlet name, version, author and
copyright notice. This is not required for
the function of the HelloClientServlet but can
provide valuable information to the user of
a Servlet who sees the returned text in the
administration tool of the Web Server.
• Compile the Servlet class
• The resulting TestingServlet.class file
should go under myApp/WEB-INF/classes
Compile the Servlet
• In the Servlet container each application is
represented by a servlet context
• each servlet context is identified by a unique
path prefix called context path
– For example our application is identified by /myApp
which is a directory under webapps.
• The remaining path is used in the selected
context to find the specific Servlet to run,
following the rules specified in the deployment
descriptor.
Deploy the Servlet
• The deployment descriptor is a XML file called web.xml
that resides in the WEB-INF directory whitin an
application.
<web-app xmlns=http://java.sun.com/xml/ns/j2ee……>
<display-name>test</display-name>
<description>test example</description>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testing</servlet-name>
<url-pattern>/servlet/TestingServlet</url-pattern>
</servlet-mapping>
</web-app>
Deployment Descriptor
• To execute your Servlet, type the following
URL in the Browser’s address field:
• http://localhost/myApp/servlet/myServlet
Run the Servlet
• By default, servlets written by specializing the
HttpServlet class can have multiple threads
concurrently running its service() method.
• If you would like to have only a single thread
running a service method at a time, then your
servlet should also implement the
SingleThreadModel interface.
– This does not involve writing any extra methods,
merely declaring that the servlet implements the
interface.
Running service() on a single thread
public class SurveyServlet extends HttpServlet
implements SingleThreadModel
{
/* typical servlet code, with no threading concerns
* in the service method. No extra code for the
* SingleThreadModel interface. */
...
}
Example

More Related Content

What's hot

Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsJavaEE Trainers
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Core web application development
Core web application developmentCore web application development
Core web application developmentBahaa Farouk
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 

What's hot (20)

Servlets
ServletsServlets
Servlets
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Servlets
ServletsServlets
Servlets
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Servlets
ServletsServlets
Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Core web application development
Core web application developmentCore web application development
Core web application development
 
Servlets
ServletsServlets
Servlets
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Servlets
ServletsServlets
Servlets
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 

Similar to Servlet Fundamentals Guide

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
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesbharathiv53
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Arun Gupta
 
Liit tyit sem 5 enterprise java unit 1 notes 2018
Liit tyit sem 5 enterprise java  unit 1 notes 2018 Liit tyit sem 5 enterprise java  unit 1 notes 2018
Liit tyit sem 5 enterprise java unit 1 notes 2018 tanujaparihar
 
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
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache TomcatAuwal Amshi
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 

Similar to Servlet Fundamentals Guide (20)

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
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
 
Liit tyit sem 5 enterprise java unit 1 notes 2018
Liit tyit sem 5 enterprise java  unit 1 notes 2018 Liit tyit sem 5 enterprise java  unit 1 notes 2018
Liit tyit sem 5 enterprise java unit 1 notes 2018
 
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 container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 

Recently uploaded

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Recently uploaded (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

Servlet Fundamentals Guide

  • 2. What can you build with Servlets? • Search Engines • E-Commerce Applications • Shopping Carts • Product Catalogs • Intranet Applications • Groupware Applications: – bulletin boards – file sharing
  • 3. Servlets vs. CGI • A Servlet does not run in a separate process. • A Servlet stays in memory between requests. • A CGI program needs to be loaded and started for each CGI request. • There is only a single instance of a servlet which answers all requests concurrently. Browser 1 Web Server Browser 2 Browser N Perl 1 Perl 2 Perl N Browser 1 Web Server Browser 2 Browser N Servlet
  • 4. • Performance – The performance of servlets is superior to CGI because there is no process creation for each client request. – Each request is handled by the servlet container process. – After a servlet has completed processing a request, it stays resident in memory, waiting for another request. • Portability – Like other Java technologies, servlet applications are portable. • Rapid development cycle – As a Java technology, servlets have access to the rich Java library that will help speed up the development process. • Robustness – Servlets are managed by the Java Virtual Machine. – Don't need to worry about memory leak or garbage collection, which helps you write robust applications. • Widespread acceptance – Java is a widely accepted technology. Benefits of Java Servlets
  • 5. • A servlet is a Java class that can be loaded dynamically into and run by a special web server. • This servlet-aware web server, is known as servlet container. • Servlets interact with clients via a request-response model based on HTTP. • Therefore, a servlet container must support HTTP as the protocol for client requests and server responses. • A servlet container also can support similar protocols such as HTTPS (HTTP over SSL) for secure transactions. Definitions
  • 6. Browser HTTP Server Static Content Servlet Container HTTP Request HTTP Response Servlet Servlet Container Architecture
  • 7. Receive Request is servlet loaded? is servlet current? Send Response Process Request Load Servlet Yes Yes No No How Servlets Work
  • 8. Servlet APIs • Every servlet must implement javax.servlet.Servlet interface • Most servlets implement the interface by extending one of these classes –javax.servlet.GenericServlet –javax.servlet.http.HttpServlet
  • 9. Generic Servlet & HTTP Servlet GenericServletGenericServlet service ( )Server ClientClient HTTPServletHTTPServlet service ( )HTTP Server BrowserBrowser request response doGet( ) doPost( ) request response
  • 10. Interface javax.servlet.Servlet • The Servlet interface defines methods – to initialize a servlet – to receive and respond to client requests – to destroy a servlet and its resources – to get any startup information – to return basic information about itself, such as its author, version and copyright. • Developers need to directly implement this interface only if their servlets cannot (or choose not to) inherit from GenericServlet or HttpServlet. Life Cycle Methods
  • 11. • void init(ServletConfig config) – Initializes the servlet. • void service(ServletRequest req, ServletResponse res) – Carries out a single request from the client. • void destroy() – Cleans up whatever resources are being held (e.g., memory, file handles, threads) and makes sure that any persistent state is synchronized with the servlet's current in-memory state. • ServletConfig getServletConfig() – Returns a servlet config object, which contains any initialization parameters and startup configuration for this servlet. • String getServletInfo() – Returns a string containing information about the servlet, such as its author, version, and copyright. GenericServlet - Methods
  • 13. HttpServlet - Methods • void doGet (HttpServletRequest request, HttpServletResponse response) –handles GET requests • void doPost (HttpServletRequest request, HttpServletResponse response) –handles POST requests • void doPut (HttpServletRequest request, HttpServletResponse response) –handles PUT requests • void doDelete (HttpServletRequest request, HttpServletResponse response) – handles DELETE requests
  • 14. Servlet Request Objects • provides client request information to a servlet. • the servlet container creates a servlet request object and passes it as an argument to the servlet's service method. • the ServletRequest interface define methods to retrieve data sent as client request: –parameter name and values – attributes – input stream • HTTPServletRequest extends the ServletRequest interface to provide request information for HTTP servlets
  • 15. HttpServletRequest - Methods Enumeration getParameterNames() an Enumeration of String objects, each String containing the name of a request parameter; or an empty Enumeration if the request has no parameters java.lang.String[] getParameterValues (java.lang.String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. java.lang.String getParameter (java.lang.String name) Returns the value of a request parameter as a String, or null if the parameter does not exist.
  • 16. HttpServletRequest - Methods Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this request. java.lang.String getMethod() Returns the name of the HTTP method with whichthi request was made, for example, GET, POST, or PUT. java.lang.String getQueryString() Returns the query string that is contained in the request URL after the path. HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one.
  • 17. Servlet Response Objects • Defines an object to assist a servlet in sending a response to the client. • The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.
  • 18. HttpServletResponse - Methods java.io.PrintWriter getWriter() Returns a PrintWriter object that can send character text to the client void setContentType (java.lang.String type) Sets the content type of the response being sent to the client. The content type may include the type of character encoding used, for example, text/html; charset=ISO-8859-4 int getBufferSize() Returns the actual buffer size used for the response
  • 19. • Create a directory structure under Tomcat for your application. • Write the servlet source code. • Compile your source code. • deploy the servlet • Run Tomcat • Call your servlet from a web browser Steps to Running a Servlet
  • 20. • The webapps directory is the Tomcat installation dir (CATALINA_HOME) is where you store your web applications. • A web application is a collection of servlets and other contents installed under a specific subset of the server's URL namespace. • A separate directory is dedicated for each servlet application. • Create a directory called myApp under the webapps directory. • Create the src and WEB-INF directories under myApp, and create a directory named classes under WEB-INF. – The src directory is for your source files, and the classes directory under WEB-INF is for your Java classes. – If you have html files, you put them directly in the myApp directory. • The admin, ROOT, and examples directories are for applications created automatically when you install Tomcat Create a Directory Structure
  • 21. • Servlets implement the javax.servlet.Servlet interface. • Because most servlets extend web servers that use the HTTP protocol to interact with clients, the most common way to develop servlets is by specializing the javax.servlet.http.HttpServlet class. • The HttpServlet class implements the Servlet interface by extending the GenericServlet base class, and provides a framework for handling the HTTP protocol. • Its service() method supports standard HTTP requests by dispatching each request to a method designed to handle it. • In myApp/src, create a file called TestingServlet.java Write the Servlet Code
  • 22. Servlet Example 1: import java.io.*; 2: import javax.servlet.*; 3: import javax.servlet.http.*; 4: 5: public class MyServlet extends HttpServlet 6: { 7: protected void doGet(HttpServletRequest req, 8: HttpServletResponse res) 9: { 10: res.setContentType("text/html"); 11: PrintWriter out = res.getWriter(); 12: out.println( "<HTML><HEAD><TITLE> Hello You!” + 13: “</Title></HEAD>” + 14: “<Body> HelloYou!!!</BODY></HTML>“ ); 14: out.close(); 16: } 17: }
  • 23. An Example of Servlet (I) Lines 1 to 3 import some packages which contain many classes which are used by the Servlet (almost every Servlet needs classes from these packages). The Servlet class is declared in line 5. Our Servlet extends javax.servlet.http.HttpServlet, the standard base class for HTTP Servlets. In lines 7 through 16 HttpServlet's doGet method is getting overridden
  • 24. An Example of Servlet (II) In line 12 we request a PrintWriter object to write text to the response message. In line 11 we use a method of the HttpServletResponse object to set the content type of the response that we are going to send. All response headers must be set before a PrintWriter or ServletOutputStream is requested to write body data to the response. In lines 13 and 14 we use the PrintWriter to write the text of type text/html (as specified through the content type).
  • 25. An Example of Servlet (III) The PrintWriter gets closed in line 15 when we are finished writing to it. In lines 18 through 21 we override the getServletInfo() method which is supposed to return information about the Servlet, e.g. the Servlet name, version, author and copyright notice. This is not required for the function of the HelloClientServlet but can provide valuable information to the user of a Servlet who sees the returned text in the administration tool of the Web Server.
  • 26. • Compile the Servlet class • The resulting TestingServlet.class file should go under myApp/WEB-INF/classes Compile the Servlet
  • 27. • In the Servlet container each application is represented by a servlet context • each servlet context is identified by a unique path prefix called context path – For example our application is identified by /myApp which is a directory under webapps. • The remaining path is used in the selected context to find the specific Servlet to run, following the rules specified in the deployment descriptor. Deploy the Servlet
  • 28. • The deployment descriptor is a XML file called web.xml that resides in the WEB-INF directory whitin an application. <web-app xmlns=http://java.sun.com/xml/ns/j2ee……> <display-name>test</display-name> <description>test example</description> <servlet> <servlet-name>Testing</servlet-name> <servlet-class>TestingServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Testing</servlet-name> <url-pattern>/servlet/TestingServlet</url-pattern> </servlet-mapping> </web-app> Deployment Descriptor
  • 29. • To execute your Servlet, type the following URL in the Browser’s address field: • http://localhost/myApp/servlet/myServlet Run the Servlet
  • 30. • By default, servlets written by specializing the HttpServlet class can have multiple threads concurrently running its service() method. • If you would like to have only a single thread running a service method at a time, then your servlet should also implement the SingleThreadModel interface. – This does not involve writing any extra methods, merely declaring that the servlet implements the interface. Running service() on a single thread
  • 31. public class SurveyServlet extends HttpServlet implements SingleThreadModel { /* typical servlet code, with no threading concerns * in the service method. No extra code for the * SingleThreadModel interface. */ ... } Example

Editor's Notes

  1. In the Request Processing phase a JSP page is handled exactly like a regular servlet. Servlets follow a three-phase life cycle: initialization, service, and destruction, with initialization and destruction typically performed once, and service performed many times. Initialization is the first phase of the Servlet life cycle and represents the creation and initialization of resources the Servlet may need to service requests. For example open a db connection, read ancillary files, get runtime parameters. All Servlets must implement the javax.servlet.Servlet interface. This interface defines the init() method to match the initialization phase of a Servlet life cycle. When a container loads a Servlet, it invokes the init() method before servicing any requests. The service phase of the Servlet life cycle represents all interactions with requests until the Servlet is destroyed. The Servlet interface matches the service phase of the Servlet life cycle to the service() method. The service() method of a Servlet is invoked once per each request and is responsible for generating the response to that request. By default a Servlet is multi-threaded, meaning that typically only one instance of a Servlet is loaded by a JSP container at any given time. Initialization is done once, and each request after that is handled concurrently by threads executing the Servlet’s service() method. This implies that a developer needs to be careful in synchronizing shared resources. The destruction phase of the Servlet life cycle represents when a Servlet is being removed from use by a container. The Servlet interface defines the destroy() method to correspond to the destruction life cycle phase. Each time a Servlet is about to be removed from use, a container calls the destroy() method, allowing the Servlet to gracefully terminate and tidy up any resources it might have created. For example closing files, db connections. Init() and destroy() methods can be overwritten by the JSP page author. Service() methos is generated automatically during translation phase and should neve be overwritten.