Вы находитесь на странице: 1из 13

JAVA SERVLET

1. INTRODUCTION

The rise of server-side Java applications is one of the latest and most exciting
trends in Java programming. The Java language was originally intended for use in
small, embedded devices. It was first hyped as a language for developing elaborate
client -side web content in the form of applets. Until recently, Java’s potential as a
server-side development platform had been sadly overlooked. Now, Java is coming
into its own as a language ideally suited for server-side development.
Businesses in particular have been quick to recognize Java’s potential on the
server—Java is inherently suited for large client/server applications. The cross-
platform nature of Java is extremely useful for organizations that have a
heterogeneous collection of servers running various flavors of the Unix and Windows
operating systems. Java’s modern, object-oriented, memory-protected design allows
developers to cut development cycles and increase reliability. In addition, Java’s
built-in support for networking and enterprise APIs provides access to legacy data,
easing the transition from older client/server systems.
Java servlets are a key component of server-side Java development. A servlet
is a small, pluggable extension to a server that enhances the server’s functionality.
Servlets allow developers to extend and customize any Java-enabled server—a web
Server, a mail server, an application server, or any custom server—with a hitherto
unknown degree of portability, flexibility, and ease. But before we go into any more
detail, let’s put things into perspective.

1.1 A BRIEF HISTORY OF THE WEB


A Web transaction involves two participants: the browser and the server. As
originally conceived, the browser was supposed to be a very simple, lightweight
program that would allow users to navigate through data. This data could consist of
plain text, HTML, images, and so on, and the browser would render all the data in a
way that humans could understand and interact with. Data could be interconnected,
and the browser would render references between documents as an image or text that
could be clicked or otherwise selected.

SSGMCE, SHEGAON 1
JAVA SERVLET

The server is an equally complex program. The server is responsible for


finding the data requested by the browser, packaging the data for transmission, and
sending it back to the browser. In the simplest kind of Web transaction, the browser
asks for a single document from the server, and the server retrieves this data and sends
it back, at which point the browser renders it in an appropriate way for the user. This
whole process is shown in figure 1.1.

Fig. 1.1

1.2 BASIC DYNAMIC PAGE GENERATION

Fortunately, a solution to the problem of dynamic content has been available


since the earliest days of the Web. Rather than reading the data from a file, the server
can run a program in order to generate the data. As far as the browser is concerned,
this situation is identical to that when the data comes from a file. The browser doesn't
care whether the server obtains its data by reading a file or running a program, as long
as what it gets back is valid HTML. However, the fact that a program is being run
behind the scenes enables the content to be dynamic. As shown in fig.1.2 the
mechanism by which the server and the HTML-generating program communicate is
called CGI (common gateway interface). Over time, the terminology has shifted
somewhat, and the programs themselves are now usually referred to as CGIs.CGI
script may be written in c, perl or any other languages.
Java Applets also provide dynamic pages but run in the web browser. Java was
introduced to embed greater interactivity into WebPages. Java has accomplished
through this with the help of applet. Applets add functionality to the WebPages like
adding games to webpages, adding graphics etc. Java applets are programs that are

SSGMCE ,SHEGAON 2
JAVA SERVLET

Embedded in the webpages, when a browser loads a webpage the applet byte code is
downloaded and executed by the browser.
Microsoft’s Active server pages uses a suite of technologies that allows
dynamically-generated content. A series of objects and components that are executed
on the web server
Java servlets are one of the options for server-side that gives portability
,efficiency and power of java.

2. SERVLETS

2.1 DEFINITION

Java Servlets/JSP are part of the Sun’s J2EE Enterprise Architecture. It is a


simple, consistent mechanism for extending the functionality of a web server. They
are precompiled Java programs that are executed on the server side and require a
Servlet container to run in. The purpose of a servlet is to create a Web page in
response to a client request. Servlets are written in Java, with a little html mixed. JSP
(Java Server Pages) is an alternate way of creating servlets JSP is translated into a
Java servlet, which is then compiled. Servlets are run in the usual way and browser
or other client sees only the resultant html as shown in fig.1.3.

SSGMCE ,SHEGAON 3
JAVA SERVLET

Fig.1.3
A Servlet is a Java class in Java EE that conforms to the Java Servlet API, a
protocol by which a Java class may respond to HTTP requests A servlet is a Java
programming language class used to extend the capabilities of servers that host
applications accessed via a request-response programming model. Although servlets
can respond to any type of request, they are commonly used to extend the applications
hosted by Web servers. For such applications, Java Servlet technology defines HTTP-
specific servlet classes.. Thus, a software developer may use a servlet to add dynamic
content to a Web server using the Java platform. The generated content is commonly
HTML, but may be other data such as XML. Servlets are the Java counterpart to non-
Java dynamic Web content technologies such as CGI and ASP.NET. Servlets can
maintain state in session variables across many server transactions by using HTTP
cookies, or URL rewriting.
The servlet API, contained in the Java package hierarchy javax.servlet, defines
the expected interactions of a Web container and a servlet. A Web container is
essentially the component of a Web server that interacts with the servlets. The Web
container is responsible for managing the lifecycle of servlets, mapping a URL to a
particular servlet and ensuring that the URL requester has the correct access rights.

SSGMCE ,SHEGAON 4
JAVA SERVLET

Servlets can be generated automatically from JavaServer Pages (JSP) by the


JavaServer Pages compiler. The difference between Servlets and JSP is that Servlets
typically embed HTML inside Java code, while JSPs embed Java code in HTML.
While the direct usage of Servlets to generate HTML (as shown in the example
below) is relatively rare nowadays, the higher level MVC web framework in Java EE
(JSF) still explicitly uses the Servlet technology for the low level request/response
handling via the FacesServlet. Fig.2.2 of the model-view-controller pattern is shown.

Fig.2.2
In the fig., model is an object that defines the component's state described in
Javabeans. View is a visual screen representation in jsp of a component and
controller is an object that makes a component respond to user input which is servlet
code.

2.2 WEBSERVER FOR SERVLETS

The complete servlet specification was created by Sun Microsystems, with


version 1.0 finalized in June 1997. Starting with version 2.3, the servlet specification
was developed under the Java Community Process. JSR 53 defined both the Servlet
2.3 and JavaServer Page 1.2 specifications. JSR 154 specifies the Servlet 2.4 and 2.5
specifications. As of March 26, 2010, the current version of the servlet specification.

SSGMCE ,SHEGAON 5
JAVA SERVLET

Many web servers like Apache,IIS,glassfish supports servlets. Tomcat is a


built-in servlet engine in the Apache server, it is open source. It is most widely used
web server in the world because it is Robust, fast, powerful and available for every
operating system but it is not very easy to manage and administrate.
The standard place to put servlet class file is tomcat_home/webapps/ROOT/
WEB-INF/classes and the jar file is put in the tomcat_home/lib directory ,we also set
the classpath of jar file sothat jvm can find the class.

3. SERVLET CLASS HIERARCHY

The most basic servlet definitions live in the javax.servlet package and consist
of a number of interfaces. Servlet architecture represented in fig.3.1.

The ServletContext interface provides a means for servlets to communicate


with the surrounding Web server or application server. This communication can take
the form of requests for system resources, reports written by the servlet to a log file,
and so on. Indirectly, the ServletContext also allows servlets to communicate with one
another, primarily by sending requests to other pages. This is how the jsp:forward and
jsp:include tags are implemented, as will be seen shortly. ServletContext is
implemented by people writing the Web or application server; servlet authors seldom
need to use it directly and never need to extend it.
The ServletConfig interface provides a mechanism for the web Server to pass
initialization information to the servlet's init() method. This information takes the
form of pairs of names and values, which are stored in a configuration file called
web.xml,
The javax.servlet package also defines three other classes. Two are the
ServletInputStream and ServletOutputStream classes, which servlets use to read and
write data, respectively. The third class, GenericServlet, implements both the Servlet
and ServletConfig interfaces and forms the basis for most real servlets.
The Web-specific versions of the servlet classes are included in a package
called javax.servlet.http. The heart of this package is the HttpServlet class, which
extends GenericServlet. This class's service() method takes HttpServletRequest and

SSGMCE ,SHEGAON 6
JAVA SERVLET

HttpServletResponse objects, instead of the generic versions from the javax.servlet


package. These variations contain a great deal of HTTP-specific information, such as
cookies, remote user names, authentication schemes, and so on.
The HttpServlet class also has provided a built-in service() method, which
looks at what kind of request has been received and calls an appropriate method to
handle it. For example, if the request were an HTTP GET, the doGet() method will be
called. There is also a doPost() method, doDelete(), and so on. This frees a servlet
writer from worrying about handing specific requests properly. A servlet writer will
simply override the appropriate do method or methods; if any other kind of request
comes in, the servlet will report that it does not handle that kind of request.

Servlet

Fig.3.1

4.Servlet Life Cycle

The servlet lifecycle consists of the following steps:

1. The servlet class is loaded by the Web container during start-up.


2. The container calls the no-arg constructor.

SSGMCE ,SHEGAON 7
JAVA SERVLET

3. The Web container calls the init() method. the servlet engine loads the
servlet’s *.class This method initializes the servlet and must be called before
the servlet can service any requests. In the entire life of a servlet, the init()
method is called only once.
4. After initialization, the servlet can service client requests. Each request is
serviced in its own separate thread. The Web container calls the service()
method of the servlet for every request. The service() method determines the
kind of request being made and dispatches it to an appropriate method to
handle the request. The developer of the servlet must provide an
implementation for these methods. If a request for a method that is not
implemented by the servlet is made, the method of the parent class is called,
typically resulting in an error being returned to the requester. when a servlet
request is made a ServletRequest object is sent with all information about the
request and a ServletResponse object is used to return the response.

5. Finally, the Web container calls the destroy() method that takes the servlet out
of service. The destroy() method, like init(), is called only once in the lifecycle
of a servlet.

SSGMCE ,SHEGAON 8
JAVA SERVLET

Fig.4.1

5.JAVA SERVLET EXAMPLE

Servlet is way to replacement of CGI technology. Servlet works on request


and response system with http client and server side. Servlet take request and give it
to server and server process, request and send back response to http browser or client.
Here we have a servlet example. How to write first servlet, This servlet examples
helps to write servlet. Write this servlet code in nodepad of or any editor and save this
servlet example with java extension.

This first servlet java file should be saved in webapps of tomcat in your
application context in WEB-INF in classes and compile it, Run javac command in
command prompt. Servlet does not contain main method. So servlet can not run on
java directly, mean like simple java program, servlet can not execute on command
prompt. You can execute servlet on web browser, but servlet class file should be in
tomcat web server of WEB-INF/classes folder. When we try compile first servlet
example, classpath of tomcat/lib/servlet-api.jar jar file should be set.

javac first.java

// Java servlet Document

import java.io.*;

SSGMCE ,SHEGAON 9
JAVA SERVLET

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class first extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("this is First servlet Example ");
}
}
When we type in the browser http://localhost:8080/servlet/first
This program give the output as this is First servlet Example.

6. ADVANTAGES OVER CGI

6.1 EFFICIENT

With traditional CGI, a new process is started for each HTTP request. If
the CGI program itself is relatively short, the overhead of starting the process can
dominate the execution time. With servlets, the Java Virtual Machine stays running
and handles each request using a lightweight Java thread, not a heavyweight operating
system process. Similarly, in traditional CGI, if there are N simultaneous requests to
the same CGI program, the code for the CGI program is loaded into memory N times.
With servlets, however, there would be N threads but only a single copy of the servlet
class. Finally, when a CGI program finishes handling a request, the program
terminates. This makes it difficult to cache computations, keep database connections
open, and perform other optimizations that rely on persistent data. Servlets, however,
remain in memory even after they complete a response, so it is straight forward to
store arbitrarily complex data between requests.
6.2 CONVENIENT

Servlets have an extensive infrastructure for automatically parsing and


decoding HTML form data, reading and setting HTTP headers, handling cookies,

SSGMCE ,SHEGAON 10
JAVA SERVLET

tracking sessions, and many other such high-level utilities. Besides, you already know
the Java programming language. Why learn Perl too? You’re already convinced that
Java technology makes for more reliable and reusable code than does C++. Why go
back to C++ for server-side programming?

6.3 PORTABLE

Servlets are written in the Java programming language and follow a standard
API. Consequently, servlets written for, say, I-Planet Enterprise Server can run
virtually unchanged on Apache, Microsoft Internet Information Server (IIS), IBM
WebSphere, or StarNine WebStar. For example, virtually all of the servlets and JSP
pages in this book were executed on Sun’s Java Web Server, Apache Tomcat and
Sun’s JavaServer Web Development Kit (JSWDK) with no changes whatsoever in the
code. Many were tested on BEA WebLogic and IBM WebSphere as well. In fact,
servlets are supported directly or by a plug-in on virtually every major Web server.
They are now part of the Java 2 Platform, Enterprise Edition (J2EE), so industry
support for servlets is becoming more pervasive.

6.4 SECURE

One of the main sources of vulnerabilities in traditional CGI programs stems


from the fact that they are often executed by general-purpose operating system shells.
So the CGI programmer has to be very careful to filter out characters such as
backquotes and semicolons that are treated specially by the shell. A second source of
problems is the fact that some CGI programs are processed by languages that do not
automatically check array or string bounds. So programmers who forget to do this
check themselves open their system up to deliberate or accidental buffer overflow
attacks. Servlets suffer from neither of these problems. Even if aservlet executes a
remote system call to invoke a program on the local operating system, it does not use
a shell to do so. And of course array bounds checking and other memory protection
features are a central part of the Java programming language.

SSGMCE ,SHEGAON 11
JAVA SERVLET

6.5 INEXPENSIVE

There are a number of free or very inexpensive Web servers available


that are good for “personal” use or low-volume Web sites. However, with the major
exception of Apache, which is free, most commercial-quality Web servers are
relatively expensive. Nevertheless, once you have a Web server, no matter its cost,
adding servlet support to it (if it doesn’t come preconfigured to support servlets) costs
very little extra. This is in contrast to many of the other CGI alternatives, which
require a significant initial investment to purchase a proprietary package.

7. CONCLUSION

The servlet API provides the foundation on which JSPs are built, and
understanding this API can come in handy for page authors. The servlet API defines a
life cycle for servlets, starting with an init() method that is called when the servlet first
loads, a service() method that is called for each request, and a destroy() method that is
called before the servlet is retired. The init() method may allocate resources that
requests will later need, and destroy() can free these resources. The service() method
is passed a request and a response object, which it uses to get information about the
request, set information about the response, and send the data.
JSPs are ultimately servlets. Thus, for pages with any significant amount
of HTML, a JSP will almost always be the preferred means of creating pages, as it is
easier to read and maintain and it avoids all the print statements. On the other hand,
pages that are dominated mostly by code expressing page logic may be better off as a
servlet, as this will avoid having to put everything in scriptlets. Servlets can also
interact with JSPs,using beans as an intermediary. Typically, the servlet will do the
computation, build a bean with the results, and send the bean on to the JSP for
formatting, using the forward() method. This provides the cleanest separation between
logic and presentation.

SSGMCE ,SHEGAON 12
JAVA SERVLET

8. REFERENCE
1. ‘Javaserver Pages ‘ Book by ‘’Larne Peckowesky”.

2. ‘Core Servlet and JSP’ Book by “Marty Hall”.

3. www.java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.

4. www.easywayserver.com.

SSGMCE ,SHEGAON 13

Вам также может понравиться