What Is a Servlet?

Download Report

Transcript What Is a Servlet?

Java Servlets
Agenda:
 What
is a servlet?
 The Advantages of Servlets Over
"Traditional" CGI
 Servlet Architecture
 The Servlet Life Cycle
 Types of Servlets
 How servlets work?
 javax.servlet & javax.servlet.http
packages
What Is a Servlet?
•Servlets are server-side Java applications, as opposed to
client-side applets or standalone applications.
•While servlets are compatible with many different types of
servers, typically they are used in web servers, as a
replacement for CGI scripts or Active-Server Pages
(ASP).
• In generic terms, a servlet is any class that can be
invoked and executed on a server, most likely on
behalf of a client. Unlike applets, which do their work
on the client, servlets do their work on the server
• Another way of phrasing what servlets do is "serverside Java." Since servlets are written in Java and are
part of the J2EE specification, they have access to all
the functionality and cross-platform portability of the
Java programming language.
The Advantages of Servlets Over
"Traditional" CGI

Efficient




Convenient


Threads instead of OS processes, one servlet
copy,persistence
With servlets, the Java virtual machine stays running and
handles each request with a lightweight Java thread, not a
heavyweight operating system process.
Servlets, however, remain in memory even after they complete
a response, so it is straightforward to store arbitrarily complex
data between client requests.
Servlets have an extensive infrastructure for automatically
parsing and decoding HTML form data, reading and setting
HTTP headers, handling cookies, tracking sessions, and many
other such high-level utilities
Powerful

Sharing data, pooling & persistence
The Advantages of Servlets Over
"Traditional" CGI ……..contd
 Portable

Run on virtually all operatings systems and web servers
 Secure

No shell escapes, no buffer overflows
 Inexpensive
cbt:
array bounds checking and other memory protection
features are a central part of the Java programming
language
Servlets Architecture:
 Following
diagram shows the position of
Servelts in a Web Application.
Servlets Tasks:
Servlets perform the following major tasks:
 Read the explicit data sent by the clients (browsers). This
includes an HTML form on a Web page or it could also come
from an applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients
(browsers). This includes cookies, media types and
compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may
require talking to a database, executing an RMI or CORBA call,
invoking a Web service, or computing the response directly.
 Send the explicit data (i.e., the document) to the clients
(browsers). This document can be sent in a variety of formats,
including text (HTML or XML), binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This
includes telling the browsers or other clients what type of
document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
Types of Servlets

Servlets must implement the interface
javax.servlet.Servlet.
There are two main types of servlets:
1)
2)
Generic servlets extend
javax.servlet.GenericServlet.
Generic servlets are protocol independent,
meaning that they contain no inherent support for
HTTP or any other transport protocol.
HTTP servlets extend javax.servlet.http.HttpServlet.
These servlets have built-in support for the HTTP
protocol and are much more useful in an Browser
environment
Types of Servlet…contd

So basically Generic Servlets are non web based
servlets and Http servlets are web based servlets

All Servlets must implement a service() method. This
method is responsible for handling requests made to
the Servlet. For generic Servlets, you simply override
the service() method to provide routines for handling
requests. HTTP Servlets provide a service method that
automatically routes the request to another method in
the servlet based on which HTTP transfer method is
used, so for HTTP Servlets you would override
doPost() to process POST requests, doGet() to
process GET requests, and so on.
How servlets work?

Servlets are created and managed at run time by the Servlet
engine, that runs inside the Java server.

The input data on which servlets operate is encapsulated in an
object called the request object. A Servlets response to a
query is encapsulated in an object called the response object.

Servlets call EJBs to perform business logic functions. Servlets
call JSPs to perform page layout functions.

Servlets control user sessions in order to provide some
persistence of user information between interactions.

Servlets can be a part of a particular application, or they can
reside separately in order to be available to multiple
applications. The latter type are said to be members of the
generic ("Default") application.

Servlets can be dynamically reloaded while the server is
running

Servlets are addressable as URLs. The buttons on your
application's pages usually point to servlets. Servlets can also
call other servlets.
Servlets Packages:

Java Servlets are Java classes run by a web server that
has an interpreter that supports the Java Servlet
specification.
 Servlets can be created using the javax.servlet and
javax.servlet.http packages, which are a standard part of
the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development
projects.
 These classes implement the Java Servlet and JSP
specifications. At the time of writing this tutorial, the
versions are Java Servlet 2.5 and JSP 2.1.
 Java servlets have been created and compiled just like
any other Java class. After you install the servlet
packages and add them to your computer's Classpath,
you can compile servlets with the JDK's Java compiler or
Package javax.servlet
 Interfaces
 Classes
1) Servlet
1) GenericServlet
2) ServletRequest
2) ServletInputStream
3) ServletResponse
3) ServletOutputStream
4) ServletConfig
5) ServletContext
6) RequestDispatcher
7) SingleThreadModel
 Exceptions
1) ServletException
2) UnavailableException
Interface Summary
RequestDispatcher
RequestDispatcher
Servlet
Servlet
ServletConfig
ServletConfig
ServletContext
ServletContext
ServletRequest
ServletRequest
Defines an object that receives requests from the client
Defines
anthem
object
the client
and sends
tothat
any receives
resourcerequests
(such asfrom
a servlet,
and
sends
to any
(such as a servlet,
HTML
file,them
or JSP
file)resource
on the server.
HTML file, or JSP file) on the server.
Defines methods that all servlets must implement.
Defines methods that all servlets must implement.
A servlet configuration object used by a servlet
A
servlet configuration
object used to
byaaservlet
servletduring
container
used to pass information
container
used to pass information to a servlet during
initialization.
initialization.
Defines a set of methods that a servlet uses to
Defines a set of methods that a servlet uses to
communicate with its servlet container, for example, to
communicate with its servlet container, for example, to
get the MIME type of a file, dispatch requests, or write
get the MIME type of a file, dispatch requests, or write
to a log file.
to a log file.
Defines an
an object
object to
to provide
provide client
client request
request information
information
Defines
to aa servlet.
servlet.
to
Defines an object to assist a servlet in sending a
response to the client.
ServletRespon
se
SingleThread
Ensures that servlets handle only one request at a time.
Model
Class Summary
GenericServlet
Defines a generic, protocol-independent servlet.
Provides an input stream for reading binary data from
ServletInputStr
a client request, including an efficient readLine
eam
method for reading data one line at a time.
ServletOutputS Provides an output stream for sending binary data to
tream
the client.
Exception Summary
ServletException
Defines a general exception a servlet can throw when
it encounters difficulty.
UnavailableExc Defines an exception that a servlet throws to indicate
eption
that it is permanently or temporarily unavailable.
Package javax.servlet.http
 Interfaces
 Classes
1) HttpServletRequest
1) HttpServlet
2) HttpServletResponse
2) HttpUtils
3) HttpSession
3) Cookie
4) HttpSessionBindingListener
4) HttpSessionBindingEvent
5) HttpSessionContext
6) SingleThreadModel
Interface Summary
HttpServletRequest
HttpServletResponse
Extends the ServletRequest interface to provide request information for
HTTP servlets.
Extends the ServletResponse interface to provide HTTP-specific
functionality in sending a response.
HttpSession
Provides a way to identify a user across more than one page request
or visit to a Web site and to store information about that user.
HttpSessionBindingListe
ner
Causes an object to be notified when it is bound to or unbound from
a session.
HttpSessionContext
Deprecated. As of Java(tm) Servlet API 2.1 for security reasons,
with no replacement.
Class Summary
Cookie
HttpServlet
HttpSessionBindingEve
nt
HttpUtils
Creates a cookie, a small amount of information sent by a servlet to a
Web browser, saved by the browser, and later sent back to the server.
Provides an abstract class to be subclassed to create an HTTP servlet
suitable for a Web site.
Sent to an object that implements HttpSessionBindingListener
when the object is bound to or unbound from the session
Provides a collection of methods that are useful in writing HTTP
servlets.
Steps to Write a Basic Servlet
1.
Import the appropriate packages and classes, including:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
2.
Extend javax.servlet.http.HttpServlet.
public class HelloWorldServlet extends HttpServlet{
3.
Implement a service() method. The main function of
a servlet is to accept an HTTP request from a Web
Browser, and return an HTTP response. This work is
done by your servlet's service() method. The service
methods include response objects that you use to
create output and request objects used to receive data
from the client.
public void service(HttpServlet Request req,
HttpServletResponse res) throws IOException
{
Steps to Write a Basic Servlet…..contd
4.
Set the content type.
res.setContentType("text/html");
5.
Obtain a PrintWriter object to use for output.
PrintWriter out = res.getWriter();
6.
Create some HTML using the PrintWriter object
out.println("<html><head><title>Hello World!</title></head>");
out.println("<body><h1>Hello World!</h1></body></html>");
}
}
7.
Compile the servlet
Program - 1
import javax.servlet.*;
import java.io.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)
{
try{
PrintWriter output=res.getWriter();
output.println("<html><body bgcolor=blue text=red>");
output.println("<b> HELLO WORLD</b>");
output.println("</body></html>");
}catch(Exception e){}
}
}
Program - 2
Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface. Web application developers typically write
servlets that extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed to handle HTTP
requests.
Sample Code for Hello World:
Following is the sample source code structure of a servlet example to write Hello
World:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
HttpServletResponse response)
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<html><head><title>Hello World!</title></head>");
out.println("<body><h1>” +message+ “</h1></body></html>");
}
public void destroy()
{
// do nothing.
}
}
Compiling a Servlet:

Let us put above code of HelloWorld.java file and put this file in
C:\ServletDevel (Windows) then you would need to add these
directories as well in CLASSPATH.
Assuming your environment is setup properly, go in ServletDevel
directory and compile HelloWorld.java as follows:
C:\ServletDevel> javac HelloWorld.java

If the servlet depends on any other libraries, you have to include those
JAR files on your CLASSPATH as well. I have included only servletapi.jar JAR file because I'm not using any other library in Hello World
program.

This command line uses the built-in javac compiler that comes with the
Sun Microsystems Java Software Development Kit (JDK). For this
command to work properly, you have to include the location of the Java
SDK that you are using in the PATH environment variable.

If everything goes fine, above compilation would produce
HelloWorld.class file in the same directory.
Servlet Deployment:

By default, a servlet application is located at the path
<Tomcat-installation-directory>/webapps/ROOT and the
class file would reside in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

If you have a fully qualified class name of
com.myorg.MyServlet, then this servlet class must be
located in WEB-INF/classes/com/myorg/MyServlet.class.

For now, let us copy HelloWorld.class into <Tomcatinstallation-directory>/webapps/ROOT/WEB-INF/classes
and create following entries in web.xml file located in
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
Note: Instead of ROOT, you can also create your own
directory and create the WEB-INF structure in it and
place your program there.
<web-app>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
Above entries to be created inside web.xml file. There could be various entries in
this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-installationdirectory>\bin\startup.bat (on windows) and finally type
http://localhost:8080/HelloWorld
in browser's address box.
If everything goes fine, you would get following result:
THANK YOU……