Name: KALAB TESFANEH JAVA SERVLET ASSIGNMENT
ID:3201/14
SECTION B
What is Servlet?
Servlet is a java based web technology that allows to develop server
side web comps in java web application having capability to generate
dynamic web pages.
Servlet is a JEE web technology that allows to extend the
functionalities of java web server or Http Server towards processing
request and generating the response.
Servlet is a JEE module web technology which allow to develop server
side web comps in java web application as "single instance (obj)-
multiple threads comps".
.if 10 requests given to a servlet comp.. the Servlet container
creates only one object for servlet comp class but starts 10 threads
on that object representing 10 requests.
Servlet is a JEE module technology/specification providing servlet api
for vendor companies as rules and guidelines to create servlet
container software and the same servlet api will be used by the
programmers to develop the servlet comps.
A Servlet comp is a java class that implements
jakarta.servlet.Servlet(1) either directly or indirectly (part of
servlet api)
Servlet Lifecycle
The lifecycle of a servlet is controlled by the container in which the
servlet has been deployed. When a request is mapped to a servlet.
A servlet life cycle can be defined as the entire process from its
creation till the destruction. The following are the paths followed by
a servlet
• The servlet is initialized by calling the init () method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of
the JVM.
The init() Method
The init method is called only once. It is called only when the
servlet is created, and not
called for any user requests afterwards. So, it is used for one-time
initializations, just as
with the init method of applets.
The servlet is normally created when a user first invokes a URL
corresponding to the
servlet, but you can also specify that the servlet be loaded when the
server is first
started.
When a user invokes a servlet, a single instance of each servlet gets
created, with each
user request resulting in a new thread that is handed off to doGet or
doPost as
appropriate. The init() method simply creates or loads some data that
will be used
throughout the life of the servlet.
The init method definition looks like this:
public void init() throws
ServletException {
// Initialization code...
}
The service() Method
The service() method is the main method to perform the actual task.
The servlet
container (i.e. web server) calls the service() method to handle
requests coming from
the client( browsers) and to write the formatted response back to the
client.
Each time the server receives a request for a servlet, the server
spawns a new thread and calls service. The service() method checks the
HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods
as appropriate.
Here is the signature of this method:
public void service (ServletRequest
request,
ServletResponse response)
throws ServletException, IOException{}
The service () method is called by the container and service method
invokes doGe,
doPost, doPut, doDelete, etc. methods as appropriate. So you have
nothing to do with
service() method but you override either doGet() or doPost() depending
on what type of
request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each
service
request. Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML
form that has
no METHOD specified and it should be handled by doGet) method.
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST
as the METHOD
and it should be handled by doPost() method.
public void doPost (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
//Servlet code
The destroy() Method
The destroy() method is called only once at the end of the life cycle
of a servlet. This
method gives your servlet a chance to close database connections, halt
background
threads, write cookie lists or hit counts to disk, and perform other
such cleanup
activities.
After the destroy() method is called, the servlet object is marked for
garbage collection.
Servlets are Java classes which service HTTP requests and implement
the javax.serviet.Servlet interface. Web application developers
typically write servlets thatextend javax.servlet. http.HttpServlet,
an abstract class that implements the Servlet
interface and is specially designed to handle HTTP requests.
Write a Hello-world Java Servlet "HelloServlet.java" Servlets are
Java programs that runs inside a Java-capable HTTP server. A user can
invoke a servlet by issuing a specific URL from the browser (HTTP
client). In this example, we shall write a servlet called
"HelloServlet.java" and compiled into "HelloServlet.class". We shall
configure such that a client can invoke "HelloServlet.class" by issuing
URL http://hostname:port/helloapp/sayhello.
A servlet shall be kept inside a Java package (instead of the
default no-name package) for proper deployment. Let's call our
package "com.nowhere". Create a sub-directories called "com\nowhere"
under "WEB-INF\src".
How It Works?
1. We define a Java class called HelloServlet (in Line 13). Line
2 places this class in a package called com.nowhere. Hence,
we save the source file under "com\nowhere" of the
"helloapp\WEB-INF\src" directory, following the Java's standard
package directory structure.
2. We need the Servlet API library to compile this program.
Servlet API is not part of JDK or Java SE (but belongs to
Java EE, now Jakarta EE). Tomcat provides a copy of servlet
API called "servlet-api.jar" in "<CATALINA_HOME>\lib". You need
to include the Servlet JAR file in your CLASSPATH for
compilation.
3. To compile the program under JDK, we need to use the -d
option to specify the output destination directory to place
the compiled class in "helloapp\WEB-INF\class\com\nowhere"
directory.
4. // Change directory to <CATALINA_HOME>\webapps\helloapp\WEB-INF
5. cd <CATALINA_HOME>\webapps\helloapp\WEB-INF
6.
7. // Compile the source file and place the class in the specified
destination directory
javac -cp ..\..\..\lib\servlet-api.jar -d classes
src\com\nowhere\HelloServlet.java
o The option "-d classes" specifies the output destination
directory, relative to the current directory. The
output is <CATALINA_HOME>\webapps\helloapp\WEB-
INF\classes\com\nowhere\HelloServlet.class. The compiler
creates the package directory "com\nowhere"
automatically.
o The option "-cp" specifies the Servlet API, located at
<CATALINA_HOME>\lib\servlet-api.jar.
8. We don't write a servlet from scratch. Instead, we create a
servlet by sub-classing jakarta.servlet.http.HttpServlet (for
Tomcat 10+) (in Line 13).
9. As mentioned, a servlet is invoked in response to a request
URL issued by a client. Specifically, a client issues an
HTTP request, the server routes the request message to the
servlet for processing. The servlet returns a response
message to the client.
10. An HTTP request could use either GET or POST request
methods, which will be processed by the servlet's doGet() or
doPost() method, respectively.
11. In the HelloServlet, we override the doGet() method (as
denoted by the annotation @Override). The doGet() runs in
response to an HTTP GET request issued by a user via an
URL. doGet() takes two arguments, an HttpServletRequest object
and an HttpServletResponse object, corresponding to the request
and response messages.
12. The HttpServletRequest object can be used to retrieve
incoming HTTP request headers and form data. The
HttpServletResponse object can be used to set the HTTP response
headers (e.g., content-type) and the response message body.
13. In Line 21, we set the "MIME" type of the response
message to "text/html". The client need to know the message
type in order to correctly display the data received.
(Other MIME types include text/plain, image/jpeg, video/mpeg,
application/xml, and many others.) In Line 23, we retrieve a
Writer object called out for writing the response message to
the client over the network. We then use the out.println() to
print out a proper HTML page containing the message "Hello,
world!". This servlet also echoes some of the clients's
request information, and prints a random number for each
request.
14. Starting from Servlet API 3.0, we can use annotation
@WebServlet to configure the URL path of the servlet. In Line
12, we configure HelloServlet to URL path "/sayhello" (relative
to the current web context). That is, to invoke the
HelloServlet, you issue a URL
"http://localhost:8080/helloapp/sayhello"
SUBMITTED TO : Mr.ABATE
SUBMISSTION DATE : 07/05/2024