Web Servers and Servlets: Web Technologies Unit-III
The document discusses various topics related to web servers and servlets including:
- Tomcat is an open-source web server that implements servlets and JSP specifications. It is commonly used for development and deployment.
- Servlets are Java programs that run on the server and are used to handle requests and generate dynamic web page content. They provide advantages over traditional CGI scripts like improved performance.
- The servlet lifecycle includes initialization, request handling, and destruction. The Servlet API defines interfaces and classes used to develop servlets. Parameters can be read from requests, initialization, and context configuration.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100%(1)100% found this document useful (1 vote)
147 views
Web Servers and Servlets: Web Technologies Unit-III
The document discusses various topics related to web servers and servlets including:
- Tomcat is an open-source web server that implements servlets and JSP specifications. It is commonly used for development and deployment.
- Servlets are Java programs that run on the server and are used to handle requests and generate dynamic web page content. They provide advantages over traditional CGI scripts like improved performance.
- The servlet lifecycle includes initialization, request handling, and destruction. The Servlet API defines interfaces and classes used to develop servlets. Parameters can be read from requests, initialization, and context configuration.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40
Web Technologies
Unit-III
Web Servers and Servlets
Contents • Tomcat web server • Introduction to Servlets: Servlets • The Advantage of Servlets over “Traditional” CGI • Basic Servlet Structure • Simple Servlet Generating Plain Text • Compiling and Installing the Servlet • Invoking the Servlet • Lifecycle of a Servlet • The Servlet API • Reading Servlet parameters • Reading Initialization parameters • Context Parameters • Handling Http Request & Responses • Using Cookies-Session Tracking • Servlet with JDBC
11/04/2020 VFSTR University 2
Tomcat web server • A “servlet container” is like a mini server, but only for serving html, jsp and servlets.
• Some may even be easier to configure than
tomcat, but tomcat provides an easy-to-use development/deployment tool and also complies with the servlet specification best of all containers.
• Tomcat is from Apache and is open-source.
11/04/2020 VFSTR University 3
Tomcat web server • Tomcat can be used as a stand-alone servlet container.
• You can install the Apache server with
Tomcat, and then proceed to configure each for their individual purposes. (The server would relay servlet requests to Tomcat.)
11/04/2020 VFSTR University 4
What is Tomcat? • Tomcat is a Servlet container (Web server that interacts with Servlets) developed under the Jakarta Project of Apache Software Foundation • Tomcat implements the Servlet and the Java Server Pages (JSP) specifications of Sun Microsystems • Tomcat is an open-source, non commercial project – Licensed under the Apache Software License • Tomcat is written in Java (OS independent) Introduction to Servlets
11/04/2020 VFSTR University 6
What Are Servlets? • Basically, a java program that runs on the server
• Creates dynamic web pages
11/04/2020 VFSTR University 7
What Do They Do? • Handle data/requests sent by users (clients) • Create and format results • Send results back to user
11/04/2020 VFSTR University 8
Who Uses Servlets? • Servlets are useful in many business oriented websites
• … and MANY others
11/04/2020 VFSTR University 9
History • Dynamic websites were often created with CGI • CGI: Common Gateway Interface • Poor solution to today’s needs • A better solution was needed
11/04/2020 VFSTR University 10
Servlets vs. CGI • Servlet Advantages – Efficient • Single lightweight java thread handles multiple requests • Optimizations such as computation caching and keeping connections to databases open – Convenient • Many programmers today already know java – Powerful • Can talk directly to the web server • Share data with other servlets • Maintain data from request to request – Portable • Java is supported by every major web browser (through plugins) – Inexpensive • Adding servlet support to a server is cheap or free
11/04/2020 VFSTR University 11
Servlets vs. CGI • CGI Advantages – CGI scripts can be written in any language – Does not depend on servlet-enabled server
11/04/2020 VFSTR University 12
Basic Servlet Structure public class MyServlet extends HttpServlet { public void init() { // Initialization here } public void service() { // Your work happens here } public void destroy() { // release resources here } }11/04/2020 VFSTR University 13 Simple Servlet Generating Plain Text import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); } }
11/04/2020 VFSTR University 14
Compiling and Installing the Servlet • Download latest version of Tomcat Server and install it on your machine. • After installing Tomcat Server on your machine follow the below mentioned steps : Create directory structure for your application. Create a Servlet Compile the Servlet Create Deployement Descriptor for your application Start the server and deploy the application
11/04/2020 VFSTR University 15
Creating the Directory Structure • Create the above directory structure inside Apache- Tomcat\webapps directory
• All HTML, static files(images, css
etc) are kept directly under Web application folder. While all the Servlet classes are kept inside classes folder.
• The web.xml (deployment descriptor) file is kept under WEB- INF folder.
11/04/2020 VFSTR University 16
Creating a Servlet There are three different ways to create a servlet. • By implementing Servlet interface • By extending GenericServlet class • By extending HttpServlet class
• Mostly HttpServlet class is used to create a
servlet • Java program is in WEB-INF/classes/
11/04/2020 VFSTR University 17
Compiling a Servlet • To compile a Servlet a JAR file is required. • Different servers require different JAR files. • In Apache Tomcat server servlet-api.jar file is required to compile a servlet class.
Steps to compile a Servlet
• Set the Class Path. • Download servlet-api.jar file. • Paste the servlet-api.jar file inside java/jdk/jre/lib/ext directory • Compile the Servlet class.
11/04/2020 VFSTR University 18
Invoking the Servlet • Create the deployment descriptor (web.xml file)
The elements are as follows:
<web-app> represents the whole application. <servlet> is sub element of <web-app> and represents the servlet. <servlet-name> is sub element of <servlet> represents the name of the servlet. <servlet-class> is sub element of <servlet> represents the class of the servlet. <servlet-mapping> is sub element of <web-app>. It is used to map the servlet.<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.
11/04/2020 VFSTR University 19
Invoking the Servlet Start the Server and deploy the project • To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory. • One Time Configuration for Apache Tomcat Server
You need to perform 2 tasks:
• set JAVA_HOME or JRE_HOME in environment variable (It is required to start server). • Change the port number of tomcat (optional). • It is required if another server is running on same port (8080).
11/04/2020 VFSTR University 20
Lifecycle of a Servlet
• Servlet class is loaded
• Servlet instance is created • init method is invoked • service method is invoked • destroy method is invoked
The Servlet API Classes in javax.servlet package • GenericServlet • ServletInputStream • ServletOutputStream • ServletRequestWrapper • ServletResponseWrapper • ServletRequestEvent • ServletContextEvent • ServletRequestAttributeEvent • ServletContextAttributeEvent • ServletException • UnavailableException
11/04/2020 VFSTR University 24
The Servlet API Interfaces in javax.servlet.http package • HttpServletRequest • HttpServletResponse • HttpSession • HttpSessionListener • HttpSessionAttributeListener • HttpSessionBindingListener • HttpSessionActivationListener • HttpSessionContext (deprecated now)
11/04/2020 VFSTR University 25
The Servlet API Classes in javax.servlet.http package • HttpServlet • Cookie • HttpServletRequestWrapper • HttpServletResponseWrapper • HttpSessionEvent • HttpSessionBindingEvent • HttpUtils (deprecated now)
11/04/2020 VFSTR University 26
Reading Servlet parameters • Servlets handles form data parsing automatically using the following methods depending on the situation:
getParameter(): call request.getParameter() method to
get the value of a form parameter. getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames(): Call this method if you want a complete list of all parameters in the current request.
Handling Http Request & Responses • The class provides four methods to handle different types of HTTP requests – doGet – doPost – doPut – doDelete • An extension class will implement one or more of these methods • Each method is called with two parameters – A request parameter containing data about the request – A response parameter that is used by the servlet to create the response • doGet and doPut are the only methods used in this text
11/04/2020 VFSTR University 30
Handling Http Request & Responses • The HTTP request is mapped to a servlet by the servlet container – A configuration file provides a standard way of mapping paths to servlet classes • The HttpServletResponse object passed as a parameter to doGet and doPost provides a PrintWriter object • Output sent to the PrintWriter object will become part of the response • The HttpServletResponse object has a setContentType method that takes the MIME type of the response as a parameter
11/04/2020 VFSTR University 31
Using Cookies-Session Tracking Cookies • HTTP is a stateless protocol, that is, the server treats each request as completely separate from any other • This, however, makes some applications difficult – A shopping cart is an object that must be maintained across numerous requests and responses • The mechanism of cookies can be used to help maintain state by storing some information on the browser system • A cookie is a key/value pair that is keyed to the domain of the server – This key/value pair is sent along with any request made by the browser of the same server • A cookie has a lifetime which specifies a time at which the cookie is deleted from the browser
11/04/2020 VFSTR University 32
Cookies & Security • Cookies are only returned to the server that created them • Cookies can be used to determine usage patterns that might not otherwise be ascertained by a server • Browsers generally allow users to limit how cookies are used – Browsers usually allow users to remove all cookies currently stored by the browser • Systems that depend on cookies will fail if the browser refuses to store them
11/04/2020 VFSTR University 33
Servlet Support for Cookies • The Java servlet support library defines a Cookie class – Methods are provided to set the comment, set a maximum age, and set a value – Other methods retrieve data from the object • The HttpServletResponse object has an addCookie method • Cookies must be added before setting content type in the response • The HttpServletRequest object has a getCookies method that returns an array of Cookies from the request
11/04/2020 VFSTR University 34
An example • The ballot example has two components – Ballot.html has a form used to cast a vote – VoteCounter.java defines a servlet which counts the votes for each candidate • The response page to a user casting a ballot carries a cookie. This is used to ‘mark’ a user as having voted • The vote tabulating servlet checks for the cookie and refuses to tabulate a vote if the cookie is provided with the request
11/04/2020 VFSTR University 35
Session Tracking • In the Java servlet framework, sessions are sets of key/value pairs • The HttpSession object implements a session • Several methods are provided to manipulate values – putValue defines a key/value pair – Invalidate destroys the session – removeValue removes a key/value pair – getValue retrieves a value given the key • A session object, if defined, is attached to the request object – The programmer can access the object – The programmer can specify on access that the session be created if it does not yet exist • An alternate vote counting servlet uses sessions to check for duplicate voting 11/04/2020 VFSTR University 36 Servlet with JDBC • Servlets can communicate with databases via JDBC (Java Database Connectivity).
• JDBC provides a uniform way for a Java program to
connect with a variety of databases in a general manner without having to deal with the specifics of those database systems.
• Many of today's applications are three-tier distributed
applications, consisting of a user interface, business logic and database access.
• The user interface in such an application is often created
using HTML or Dynamic HTML. 11/04/2020 VFSTR University 37 • Using the networking provided automatically by the browser, the user interface can communicate with the middle-tier business logic.
• The middle tier can then access the database to
manipulate the data. All three tiers may reside on separate computers that are connected to a network.
• In multi-tier architectures, Web servers are
increasingly used to build the middle tier.
• They provide the business logic that manipulates data
from databases and that communicates with client Web browsers
11/04/2020 VFSTR University 38
• Servlets, through JDBC, can interact with popular database systems.
• Developers do not need to be familiar with the
specifics of each database system.
• Rather, developers use SQL-based queries and the
JDBC driver handles the specifics of interacting with each database system.