SlideShare una empresa de Scribd logo
1 de 7
Servlets
Servlets are small programs that execute on the server side of a Web connection. Just as applets
dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of a
Web server.
Use & Advantages of Servlet
Consider a request for a static Web page.
 A user enters a Uniform Resource Locator (URL) to a browser.
 The browser generates an HTTP request to the appropriate Web server.
 The Web server maps this request to a specific file. That file is returned in an HTTP response to
the browser.
 The HTTP header in the response indicates the type of the content.
Now consider dynamic content. Assume that an online bookstore uses a database to store information
about its business, including book prices, availability, orders, and so forth. It wants to make this
information accessible to customers via Web pages. The contents of those Web pages must be
dynamically generated, to reflect the latest information in the database.
In the early days of the Web, a server could dynamically construct a page by creating a separate process
to handle each client request. The process would open connections to one or more databases in order to
obtain the necessary information. It communicated with the Web server via an interface known as the
Common Gateway Interface (CGI). CGI allowed the separate process to read data from the HTTP request
and write data to the HTTP response. A variety of different languages were used to build CGI programs,
including C, C++, and Perl.
However, CGI suffered serious performance problems. Creating a separate process for each client request
was expensive, in terms of processor and memory resources. It was also expensive to open and close
database connections for each client request. In addition, the CGI programs were not platform-
independent. Therefore, other techniques were introduced, including servlets.
Servlets offer several advantages over CGI:
 Performance is significantly better. Servlets execute within the address space of a Web server.
Creating a separate process to handle each client request isn't necessary.
 Servlets are platform-independent, because they are written in Java. Several Web servers, from
vendors such as Sun, Netscape, and Microsoft, offer the Servlets API. Programs developed for
this API can be moved to any of these environments without recompilation.
 The Java Security Manager on the server enforces a set of restrictions to protect the resources on
a server machine.
 The full functionality of the Java class libraries is available to a servlet. It can communicate with
applets, databases, or other software via the sockets and RMI mechanisms that you have seen
already.
The Life Cycle of a Servlet
Three methods are central to the life cycle of a servlet: init ( ), service ( ), and destroy ( ). They are
implemented by every servlet and are invoked at specific times by the server.
 First, assume that a user enters a Uniform Resource Locator (URL) to a Web browser. The
browser then generates an HTTP request for this URL and sends it to the appropriate server.
 Second, this HTTP request is received by the Web server. The server maps this request to a
particular servlet. The servlet is dynamically retrieved and loaded into the address space of the
server.
 Third, the server invokes the init ( ) method of the servlet. This method is invoked only when the
servlet is first loaded into memory. Initialization parameters can be passed to the servlet so that it
may configure itself.
 Fourth, the server invokes the servlet's service ( ) method, which is called to process the HTTP
request. The servlet can read data that has been provided in the HTTP request, and may also
formulate an HTTP response for the client. The servlet remains in the server's address space and
is available to process any other HTTP requests received from clients. The service ( ) method is
called for each HTTP request.
 Finally, the server may decide to unload the servlet from its memory. The algorithms by which
this determination is made are specific to each server. The server calls destroy () method to
relinquish any resources, such as file handles that are allocated for the servlet. Important data may
be saved to a persistent store. The memory allocated for the servlet and its objects can then be
garbage-collected.
Using Tomcat for Servlet Deployment
To create servlets, download a servlet development environment. The one currently recommended by Sun
is Tomcat which supports the servlet specification. Tomcat is an open source product maintained by
Jakarta Project of the Apache Software Foundation. It contains the class libraries; documentation and run-
time support which are needed to create and test servlet.
Follow the instructions to install the Tomcat on your machine. The default location for Tomcat is
C:Program FilesApache Software Foundation
Set the classpath of the servlet-api.jar file in the variable CLASSPATH inside the environment variable
by using the following steps:
For Windows XP,
Go to Start->Control Panel->System->Advanced->Environment Variables->New button and Set values:
Variable Name: CLASSPATH
Variable Value: C:Program FilesJavaTomcat 6.0libservlet-api.jar
Servlet-api.jar file contains the classes and interfaces that are needed to build servlet.
Start and Stop Tomcat
To start Tomcat, select Start Tomcat in the Start| Programs Menu, or run startup.bat from the
C:Program FilesApache Software Foundation Tomcat 6.0bin
directory. To stop Tomcat, select Stop Tomcat in the Start| Programs Menu, or run shutdown.bat.
Web Application Directory Structure
Directory Contains
C:Program FilesApache Software FoundationTomcat 7.0webappsmyApps
This is the root directory of the web application. All JSP and XHTML files are stored here.
C:Program FilesApache Software FoundationTomcat 7.0webappsmyAppsWEB-INF
This directory contains all resources related to the application that are not in the document root of the
application. This is where your web application deployment descriptor (web.xml) is located. Note that the
WEB-INF directory is not part of the public document. No files contained in this directory can be served
directly to a client.
C:Program FilesApache Software FoundationTomcat 7.0webappsmyAppsWEB-INFclasses
This directory is where servlet and utility classes are located.
C:Program FilesApache Software FoundationTomcat 7.0webapps myAppsWEB-INFlib
This directory contains Java Archive files that the web application depends upon.
A Simple Servlet (Imp)
The basic steps for building and testing a simple servlet are the following:
 Create a java source file and a web.xml file in a Tomcat directory structure.
 Compile the java source file, put the compiled file (.class file) in the classes’ folder of your
application and deploy the directory of your application in the webapps folder inside the tomcat
directory.
 Start the tomcat server, open a browser window and type the URL
http://localhost:8080/directory (folder name of your application) name/servlet name and
press enter.
Create and Compile the Servlet Source Code
To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{ response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}}
First, the program imports the javax.servlet package, which contains the classes and interfaces required
to build servlets. Next, the program defines HelloServlet as a subclass of GenericServlet. The
GenericServlet class provides functionality that makes it easy to handle requests and responses.
Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden. This
method handles requests from a client. Notice that the first argument is a ServletRequest object. This
enables a servlet to read data that is provided via the client request. The second argument is a
ServletResponse object. This enables a servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response. The MIME type
text/html indicates that the browser should interpret the content as HTML source code.
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client
as part of the HTTP response. Then, println( ) is used to write some simple HTML source code as the
HTTP response.
Compile this source code and place the HelloServlet.class file in the Tomcat class files directory as
described previously.
Create Deployment Descriptor (web.xml)
A deployment descriptor is an optional component in a servlet application, taking the form of an XML
document called web.xml. The descriptor must be located in the WEB-INF directory of the servlet
application. When present, the deployment descriptor contains configuration settings specific to that
application.
For this step, create a web.xml file and place it under the WEB-INF directory under myApp.
The web.xml for this example application must have the following content.
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testing</servlet-name>
<servlet-class>/TestingServlet</servlet-class>
</servlet-mapping>
</web-app>
Start Tomcat
As explained above.
Start a Web Browser and Request the Servlet
Start a Web browser and enter the URL shown here:
http://localhost:8080/directory name (myApps)/TestingServlet and press enter.
Alternatively, you may enter the URL shown here:
http:// 127.0.0.1:8080/ directory name (myApps)/TestingServlet
This can be done because 127.0.0.1 is defined as the IP address of the local machine.
The output of the servlet in the browser display area should contain the string Hello! In bold type.
The Servlet API
Two packages contain the code that is required to build servlets: javax.servlet and javax.servlet.http.
They constitute the Servlet API. These packages are not part of the Java core packages. Therefore, they
are not included in the Java Development Kit (JDK). Download Tomcat to obtain their functionality.
The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that establish the framework in
which servlets operate. The most significant of these is Servlet. All servlets must implement this interface
or extend a class that implements the interface. The following table summarizes the interfaces that are
provided in this package.
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access information about their
environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
SingleThreadModel Indicates that the servlet is thread safe.
The following table summarizes the classes that are provided in this package:
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a client.
ServletOutputStream Provides an output stream for writing responses to a client.
ServletException Indicates that a servlet error occurred.
UnavailableException Indicates that a servlet is permanently or temporarily
unavailable.
The javax.servlet.http Package
The javax.servlet.http package contains several interfaces and classes that are commonly used by servlet
developers. The following table summarizes the interfaces that are provided in this package:
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP request.
HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound from a session.
HttpSessionContext Allows sessions to be managed.
The following table summarizes the classes that are provided in this package. The most important of these
is HttpServlet.
Class Description
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session value.
HttpUtils Declares utility methods for servlets.
Handling HTTP Requests and Responses
The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A
servlet developer typically overrides one of these methods. These methods are doDelete ( ), doGet ( ),
doOptions ( ), doPost ( ), doPut ( ), and doTrace ( ).
However, the GET and POST methods are commonly used when handling form input.
Handling HTTP GET Requests
This section develops a servlet that handles an HTTP GET request. The servlet is invoked when a form on
a Web page is submitted.
The example contains two files: ColorGet.htm defines a Web page, and
ColorGetServlet.java defines a servlet.
ColorGet.htm defines a form that contains a select element and a submit button. Notice that the action
parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET
request.
<html><body>
<form name="Form1" method=”get” action="Servlet1">
<b><center>color:<center><b>
<select name="color" >
<option value="Red">Red</option>
<option value="Green">Green</option>
</select>
<input type=submit value="Submit">
</form></body></html>
The source code for ColorGetServlet.java is shown in the following listing. The doGet( ) method is
overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( )
method of HttpServletRequest to obtain the selection that was made by the user. A response is then
formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{ String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B><center>The selected color is: ");
pw.println(color);
pw.close(); }}
Compile the servlet and perform the following steps:
1. Start Tomcat
2. Display the Web page in the browser
3. Select a color and submit the web page
Parameters for an HTTP GET request are included as part of the URL that is sent to the Web server.
Assume that the user selects the red option and submits the form. The URL sent from the browser to the
server is the following: http://localhost:8080/servler/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string.
Deployment Descriptor should be created as discussed in the previous section.
Handling HTTP POST Requests
This section develops a servlet that handles an HTTP POST request. The servlet is invoked when a form
on a Web page is submitted. The example contains two files:
ColorPost.htm defines a Web page, and
ColorPostServlet.java defines a servlet.
ColorPost.htm is identical to ColorGet.htm except that the method parameter for the form tag explicitly
specifies that the POST method should be used, and the action parameter for the form tag specifies a
different servlet.
<html><body>
<form name="Form2" method="post" action="servlet2">
<b><center>color:<center><b>
<select name="color" >
<option value="Red">Red</option>
<option value="Green">Green</option>
</select>
<input type=submit value="Submit"></form></body></html>
The source code for ColorPostServlet.java is shown in the following listing. The doPost( ) method is
overridden to process any HTTP POST requests that are sent to this servlet. It uses the getParameter( )
method of HttpServletRequest to obtain the selection that was made by the user. A response is then
formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();}}
Compile the servlet and perform the following steps:
1. Start Tomcat
2. Display the Web page in the browser
3. Select a color and submit the web page
An HTTP POST request are not included as part of the URL that is sent to the Web server. In this
example, the URL sent from the browser to the server is the following:
http://localhost:8080/servler/ColorGetServlet
The parameter names and values are sent in the body of the HTTP request.
Deployment Descriptor should be created as discussed in the previous section.
Difference between Get and Post Method
GET is the simplest HTTP method, and it is used to ask the server to get a resource and send it back. That
resource might be an HTML page, a JPEG, a PDF, etc. The point of GET is to get something back from
the server.
POST is a more powerful request. With POST, we can request something and at the same time send
form data to the server. There are the following differences between Get & Post Methods:
Visibility - GET request is sent via the URL string (appended to the URI with a question-mark as
separator), which is visible whereas POST request is encapsulated in the body of the HTTP request and
can't be seen.
Length - Since, GET request goes via URL, so it has a limitation for its length. POST request has not
such limitation because it becomes a part of the body of the HTTP request.
Performance - GET request is comparatively faster as it's relatively simpler to create a GET request and
the time spent in the encapsulation of the POST request in the HTTP body is saved in this case.
Type of Data - GET request is sent via URL string and URL can be text-only, so GET can carry only
text data whereas POST has no such restriction and it can carry both text as well as binary data.
Caching/Bookmarking - A GET request is nothing but an URL hence it can be cached as well as
Bookmarked. A POST request can’t be bookmarked.
FORM Default - GET is the default method of the HTML FORM element. To submit a FORM using
POST method, we need to specify the method attribute and give it the value "POST".
Security Issues
Untrusted applets are constrained to operate in a "sandbox." They cannot perform operations that are
potentially dangerous to a user's machine. This includes reading and writing files, opening sockets to
arbitrary machines, calling native methods, and creating new processes. Other restrictions also apply.
Similar constraints also exist for untrusted servlets. Code that is loaded from a remote machine is
untrusted. However, trusted servlets, those loaded from the local machine, are not limited in this manner.
Questions:
1) What are the servlets? Describe the uses and advantages of servlets. (Imp)
2) Describe the life cycle of servlets and discuss the servlet API and security issues in servlets.
(M. Imp)
3) Write down the introduction to servlet and explain the servlet with a suitable example. (Imp)
4) Write a short note on Tomcat Server.
5) What is the difference between GenericServlet and HttpServlet. (M. Imp)
6) What is the Difference between Get and Post? (Imp)

Más contenido relacionado

La actualidad más candente (20)

Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Java servlets
Java servletsJava servlets
Java servlets
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Servlets
ServletsServlets
Servlets
 
Servlets
ServletsServlets
Servlets
 
JDBC
JDBCJDBC
JDBC
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Servlets
ServletsServlets
Servlets
 
Servlet
Servlet Servlet
Servlet
 
Java servlets
Java servletsJava servlets
Java servlets
 
Jsp servlets
Jsp servletsJsp servlets
Jsp servlets
 
Listeners and filters in servlet
Listeners and filters in servletListeners and filters in servlet
Listeners and filters in servlet
 

Similar a Unit5 servlets

Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache TomcatAuwal Amshi
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deploymentelliando dias
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servletsAamir Sohail
 
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
 
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
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3Ben Abdallah Helmi
 
Server side programming
Server side programming Server side programming
Server side programming javed ahmed
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3Ben Abdallah Helmi
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01raviIITRoorkee
 

Similar a Unit5 servlets (20)

Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
 
Servlets
ServletsServlets
Servlets
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
 
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
 
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
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3
 
Server side programming
Server side programming Server side programming
Server side programming
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3
 
Servers names
Servers namesServers names
Servers names
 
Servers names
Servers namesServers names
Servers names
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
Major project report
Major project reportMajor project report
Major project report
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

Unit5 servlets

  • 1. Servlets Servlets are small programs that execute on the server side of a Web connection. Just as applets dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of a Web server. Use & Advantages of Servlet Consider a request for a static Web page.  A user enters a Uniform Resource Locator (URL) to a browser.  The browser generates an HTTP request to the appropriate Web server.  The Web server maps this request to a specific file. That file is returned in an HTTP response to the browser.  The HTTP header in the response indicates the type of the content. Now consider dynamic content. Assume that an online bookstore uses a database to store information about its business, including book prices, availability, orders, and so forth. It wants to make this information accessible to customers via Web pages. The contents of those Web pages must be dynamically generated, to reflect the latest information in the database. In the early days of the Web, a server could dynamically construct a page by creating a separate process to handle each client request. The process would open connections to one or more databases in order to obtain the necessary information. It communicated with the Web server via an interface known as the Common Gateway Interface (CGI). CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response. A variety of different languages were used to build CGI programs, including C, C++, and Perl. However, CGI suffered serious performance problems. Creating a separate process for each client request was expensive, in terms of processor and memory resources. It was also expensive to open and close database connections for each client request. In addition, the CGI programs were not platform- independent. Therefore, other techniques were introduced, including servlets. Servlets offer several advantages over CGI:  Performance is significantly better. Servlets execute within the address space of a Web server. Creating a separate process to handle each client request isn't necessary.  Servlets are platform-independent, because they are written in Java. Several Web servers, from vendors such as Sun, Netscape, and Microsoft, offer the Servlets API. Programs developed for this API can be moved to any of these environments without recompilation.  The Java Security Manager on the server enforces a set of restrictions to protect the resources on a server machine.  The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. The Life Cycle of a Servlet Three methods are central to the life cycle of a servlet: init ( ), service ( ), and destroy ( ). They are implemented by every servlet and are invoked at specific times by the server.  First, assume that a user enters a Uniform Resource Locator (URL) to a Web browser. The browser then generates an HTTP request for this URL and sends it to the appropriate server.  Second, this HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server.  Third, the server invokes the init ( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. Initialization parameters can be passed to the servlet so that it may configure itself.
  • 2.  Fourth, the server invokes the servlet's service ( ) method, which is called to process the HTTP request. The servlet can read data that has been provided in the HTTP request, and may also formulate an HTTP response for the client. The servlet remains in the server's address space and is available to process any other HTTP requests received from clients. The service ( ) method is called for each HTTP request.  Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls destroy () method to relinquish any resources, such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage-collected. Using Tomcat for Servlet Deployment To create servlets, download a servlet development environment. The one currently recommended by Sun is Tomcat which supports the servlet specification. Tomcat is an open source product maintained by Jakarta Project of the Apache Software Foundation. It contains the class libraries; documentation and run- time support which are needed to create and test servlet. Follow the instructions to install the Tomcat on your machine. The default location for Tomcat is C:Program FilesApache Software Foundation Set the classpath of the servlet-api.jar file in the variable CLASSPATH inside the environment variable by using the following steps: For Windows XP, Go to Start->Control Panel->System->Advanced->Environment Variables->New button and Set values: Variable Name: CLASSPATH Variable Value: C:Program FilesJavaTomcat 6.0libservlet-api.jar Servlet-api.jar file contains the classes and interfaces that are needed to build servlet. Start and Stop Tomcat To start Tomcat, select Start Tomcat in the Start| Programs Menu, or run startup.bat from the C:Program FilesApache Software Foundation Tomcat 6.0bin directory. To stop Tomcat, select Stop Tomcat in the Start| Programs Menu, or run shutdown.bat. Web Application Directory Structure Directory Contains C:Program FilesApache Software FoundationTomcat 7.0webappsmyApps This is the root directory of the web application. All JSP and XHTML files are stored here. C:Program FilesApache Software FoundationTomcat 7.0webappsmyAppsWEB-INF This directory contains all resources related to the application that are not in the document root of the application. This is where your web application deployment descriptor (web.xml) is located. Note that the WEB-INF directory is not part of the public document. No files contained in this directory can be served directly to a client.
  • 3. C:Program FilesApache Software FoundationTomcat 7.0webappsmyAppsWEB-INFclasses This directory is where servlet and utility classes are located. C:Program FilesApache Software FoundationTomcat 7.0webapps myAppsWEB-INFlib This directory contains Java Archive files that the web application depends upon. A Simple Servlet (Imp) The basic steps for building and testing a simple servlet are the following:  Create a java source file and a web.xml file in a Tomcat directory structure.  Compile the java source file, put the compiled file (.class file) in the classes’ folder of your application and deploy the directory of your application in the webapps folder inside the tomcat directory.  Start the tomcat server, open a browser window and type the URL http://localhost:8080/directory (folder name of your application) name/servlet name and press enter. Create and Compile the Servlet Source Code To begin, create a file named HelloServlet.java that contains the following program: import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Hello!"); pw.close(); }} First, the program imports the javax.servlet package, which contains the classes and interfaces required to build servlets. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses. Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables a servlet to read data that is provided via the client request. The second argument is a ServletResponse object. This enables a servlet to formulate a response for the client. The call to setContentType( ) establishes the MIME type of the HTTP response. The MIME type text/html indicates that the browser should interpret the content as HTML source code. Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. Then, println( ) is used to write some simple HTML source code as the HTTP response. Compile this source code and place the HelloServlet.class file in the Tomcat class files directory as described previously. Create Deployment Descriptor (web.xml) A deployment descriptor is an optional component in a servlet application, taking the form of an XML document called web.xml. The descriptor must be located in the WEB-INF directory of the servlet application. When present, the deployment descriptor contains configuration settings specific to that application. For this step, create a web.xml file and place it under the WEB-INF directory under myApp. The web.xml for this example application must have the following content. <?xml version="1.0" encoding="ISO-8859-1"?> <web-app>
  • 4. <servlet> <servlet-name>Testing</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Testing</servlet-name> <servlet-class>/TestingServlet</servlet-class> </servlet-mapping> </web-app> Start Tomcat As explained above. Start a Web Browser and Request the Servlet Start a Web browser and enter the URL shown here: http://localhost:8080/directory name (myApps)/TestingServlet and press enter. Alternatively, you may enter the URL shown here: http:// 127.0.0.1:8080/ directory name (myApps)/TestingServlet This can be done because 127.0.0.1 is defined as the IP address of the local machine. The output of the servlet in the browser display area should contain the string Hello! In bold type. The Servlet API Two packages contain the code that is required to build servlets: javax.servlet and javax.servlet.http. They constitute the Servlet API. These packages are not part of the Java core packages. Therefore, they are not included in the Java Development Kit (JDK). Download Tomcat to obtain their functionality. The javax.servlet Package The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The most significant of these is Servlet. All servlets must implement this interface or extend a class that implements the interface. The following table summarizes the interfaces that are provided in this package. Interface Description Servlet Declares life cycle methods for a servlet. ServletConfig Allows servlets to get initialization parameters. ServletContext Enables servlets to log events and access information about their environment. ServletRequest Used to read data from a client request. ServletResponse Used to write data to a client response. SingleThreadModel Indicates that the servlet is thread safe. The following table summarizes the classes that are provided in this package: Class Description GenericServlet Implements the Servlet and ServletConfig interfaces. ServletInputStream Provides an input stream for reading requests from a client. ServletOutputStream Provides an output stream for writing responses to a client. ServletException Indicates that a servlet error occurred. UnavailableException Indicates that a servlet is permanently or temporarily unavailable. The javax.servlet.http Package
  • 5. The javax.servlet.http package contains several interfaces and classes that are commonly used by servlet developers. The following table summarizes the interfaces that are provided in this package: Interface Description HttpServletRequest Enables servlets to read data from an HTTP request. HttpServletResponse Enables servlets to write data to an HTTP response. HttpSession Allows session data to be read and written. HttpSessionBindingListener Informs an object that it is bound to or unbound from a session. HttpSessionContext Allows sessions to be managed. The following table summarizes the classes that are provided in this package. The most important of these is HttpServlet. Class Description Cookie Allows state information to be stored on a client machine. HttpServlet Provides methods to handle HTTP requests and responses. HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session value. HttpUtils Declares utility methods for servlets. Handling HTTP Requests and Responses The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. These methods are doDelete ( ), doGet ( ), doOptions ( ), doPost ( ), doPut ( ), and doTrace ( ). However, the GET and POST methods are commonly used when handling form input. Handling HTTP GET Requests This section develops a servlet that handles an HTTP GET request. The servlet is invoked when a form on a Web page is submitted. The example contains two files: ColorGet.htm defines a Web page, and ColorGetServlet.java defines a servlet. ColorGet.htm defines a form that contains a select element and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request. <html><body> <form name="Form1" method=”get” action="Servlet1"> <b><center>color:<center><b> <select name="color" > <option value="Red">Red</option> <option value="Green">Green</option> </select> <input type=submit value="Submit"> </form></body></html> The source code for ColorGetServlet.java is shown in the following listing. The doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorGetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html");
  • 6. PrintWriter pw = response.getWriter(); pw.println("<B><center>The selected color is: "); pw.println(color); pw.close(); }} Compile the servlet and perform the following steps: 1. Start Tomcat 2. Display the Web page in the browser 3. Select a color and submit the web page Parameters for an HTTP GET request are included as part of the URL that is sent to the Web server. Assume that the user selects the red option and submits the form. The URL sent from the browser to the server is the following: http://localhost:8080/servler/ColorGetServlet?color=Red The characters to the right of the question mark are known as the query string. Deployment Descriptor should be created as discussed in the previous section. Handling HTTP POST Requests This section develops a servlet that handles an HTTP POST request. The servlet is invoked when a form on a Web page is submitted. The example contains two files: ColorPost.htm defines a Web page, and ColorPostServlet.java defines a servlet. ColorPost.htm is identical to ColorGet.htm except that the method parameter for the form tag explicitly specifies that the POST method should be used, and the action parameter for the form tag specifies a different servlet. <html><body> <form name="Form2" method="post" action="servlet2"> <b><center>color:<center><b> <select name="color" > <option value="Red">Red</option> <option value="Green">Green</option> </select> <input type=submit value="Submit"></form></body></html> The source code for ColorPostServlet.java is shown in the following listing. The doPost( ) method is overridden to process any HTTP POST requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorPostServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close();}} Compile the servlet and perform the following steps: 1. Start Tomcat 2. Display the Web page in the browser 3. Select a color and submit the web page An HTTP POST request are not included as part of the URL that is sent to the Web server. In this example, the URL sent from the browser to the server is the following: http://localhost:8080/servler/ColorGetServlet
  • 7. The parameter names and values are sent in the body of the HTTP request. Deployment Descriptor should be created as discussed in the previous section. Difference between Get and Post Method GET is the simplest HTTP method, and it is used to ask the server to get a resource and send it back. That resource might be an HTML page, a JPEG, a PDF, etc. The point of GET is to get something back from the server. POST is a more powerful request. With POST, we can request something and at the same time send form data to the server. There are the following differences between Get & Post Methods: Visibility - GET request is sent via the URL string (appended to the URI with a question-mark as separator), which is visible whereas POST request is encapsulated in the body of the HTTP request and can't be seen. Length - Since, GET request goes via URL, so it has a limitation for its length. POST request has not such limitation because it becomes a part of the body of the HTTP request. Performance - GET request is comparatively faster as it's relatively simpler to create a GET request and the time spent in the encapsulation of the POST request in the HTTP body is saved in this case. Type of Data - GET request is sent via URL string and URL can be text-only, so GET can carry only text data whereas POST has no such restriction and it can carry both text as well as binary data. Caching/Bookmarking - A GET request is nothing but an URL hence it can be cached as well as Bookmarked. A POST request can’t be bookmarked. FORM Default - GET is the default method of the HTML FORM element. To submit a FORM using POST method, we need to specify the method attribute and give it the value "POST". Security Issues Untrusted applets are constrained to operate in a "sandbox." They cannot perform operations that are potentially dangerous to a user's machine. This includes reading and writing files, opening sockets to arbitrary machines, calling native methods, and creating new processes. Other restrictions also apply. Similar constraints also exist for untrusted servlets. Code that is loaded from a remote machine is untrusted. However, trusted servlets, those loaded from the local machine, are not limited in this manner. Questions: 1) What are the servlets? Describe the uses and advantages of servlets. (Imp) 2) Describe the life cycle of servlets and discuss the servlet API and security issues in servlets. (M. Imp) 3) Write down the introduction to servlet and explain the servlet with a suitable example. (Imp) 4) Write a short note on Tomcat Server. 5) What is the difference between GenericServlet and HttpServlet. (M. Imp) 6) What is the Difference between Get and Post? (Imp)