Java Servlets Quick Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Introduction to Java Servlets

Today we all are aware of the need of creating dynamic web pages i.e the ones which
have the capability to change the site contents according to the time or are able to
generate the contents according to the request received by the client. If you like coding
in Java, then you will be happy to know that using Java there also exists a way to
generate dynamic web pages and that way is Java Servlet. But before we move forward
with our topic let’s first understand the need for server-side extensions.
Servlets are the Java programs that runs on the Java-enabled web server or application
server. They are used to handle the request obtained from the web server, process the
request, produce the response, then send response back to the web server.
Properties of Servlets :
 Servlets work on the server-side.
 Servlets capable of handling complex request obtained from web server.
Execution of Servlets :
Execution of Servlets involves the six basic steps:
1. The clients send the request to the web server.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generate the response in the form of output.
5. The servlet send the response back to the web server.
6. The web server sends the response back to the client and the client browser
displays it on the screen.
Servlet Architecture
The following diagram shows the servlet architecture:

The server-side extensions are nothing but the technologies that are used to create
dynamic Web pages. Actually, to provide the facility of dynamic Web pages, Web pages
need a container or Web server. To meet this requirement, independent Web server
providers offer some proprietary solutions in the form of APIs(Application Programming
Interface).
These APIs allow us to build programs that can run with a Web server. In this case
, Java Servlet is also one of the component APIs of Java Platform Enterprise
Edition which sets standards for creating dynamic Web applications in Java.
Before learning about something its important to know the need for that something, its
not like that this is the only technology available for creating dynamic Web pages. The
Servlet technology is similar to other Web server extensions such as Common
Gateway Interface(CGI) scripts and Hypertext Preprocessor (PHP). However, Java
Servlets are more acceptable since they solve the limitations of CGI such as low
performance and low degree scalability.
Servlets API’s:
Servlets are build from two packages:
 javax.servlet(Basic)
 javax.servlet.http(Advance)
Various classes and interfaces present in these packages are:
COMPONENT TYPE PACKAGE

Servlet Interface javax.servlet.*

ServletRequest Interface javax.servlet.*

ServletResponse Interface javax.servlet.*

GenericServlet Class javax.servlet.*

HttpServlet Class javax.servlet.http.*

HttpServletRequest Interface javax.servlet.http.*

HttpServletResponse Interface javax.servlet.http.*

Filter Interface javax.servlet.*

ServletConfig Interface javax.servlet.*

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.

In Servlet API, I have discussed little bit about Http Servlet. In this article, I will
discuss Http Servlet in detail.

Unlike Generic Servlet, the HTTP Servlet doesn’t override the service() method.
Instead it overrides the doGet() method or doPost() method or both. The doGet()
method is used for getting the information from server while the doPost() method
is used for sending information to the server.
In Http Servlet there is no need to override the service() method because this
method dispatches the Http Requests to the correct method handler, for example
if it receives HTTP GET Request it dispatches the request to the doGet() method.

How Http Servlet works?


As you can see in the diagram below that client (user’s browser) make requests.
These requests can be of any type, for example – Get Request, Post Request,
Head Request etc. Server dispatches these requests to the servlet’s service()
method, this method dispatches these requests to the correct handler for
example if it receives Get requests it dispatches it to the doGet() method.

PrintWriter: prints text data to a character stream.

getWriter :Returns a PrintWriter object that can send character text to the client.
his is an example of the simple servlet, you will see in the next lines how to write and display html pages,
and some more complex things. Also, you will get an explenation for every line of the code.

Hello World!

This servlet will provide you with information on how to build a static content:
All the examples are available with any of our tomcat web hosting solutions.
HelloServlet.java

1: import javax.servlet.http.* 2: import javax.servlet.*;


3: import java.io.*; 4: 5: public class HelloClientServlet

extendsHttpServlet

6: {

7: protected void doGet(HttpServletRequest req,

8: HttpServletResponse res)

9: throws ServletException, IOException

10: {

11: res.setContentType("text/html");

12: PrintWriter out = res.getWriter();

13: out.println("<HTML><HEAD><TITLE>Hello World!</TITLE>"+

14: "</HEAD><BODY>Hello World!</BODY></HTML>");

15: out.close();

16: }

17:
18: public String getServletInfo()

19: {

20: return "Your first Hello Servlet!";

21: }

22: }

When this servlet is compilied you will get the "Hello World!" page.

Explaination to the lines of code:

First 3 lines indicate the packages you need to load, so you can use method and procedures of such:

1: import javax.servlet.http.*

2: import javax.servlet.*;

3: import java.io.*;
We declared the servlet class at line 5. This servlet extends javax.servlet.http.HttpServlet, the standard
base class for HTTP Servlets.

5: public class HelloClientServlet extends HttpServlet

In the lines from 7 - 16 HttpServlet's doGet method is getting overridden.

7: protected void doGet(HttpServletRequest req,

8: HttpServletResponse res)

9: throws ServletException, IOException


10: {

...

16: }

HttpServletResponse method is used at the line 11, object to set the content type of the response that we
are going to send. You must set all response headers before you request a PrintWriter or
ServletOutputStream to send body data to the response.

11: res.setContentType("text/html");

PrintWriter object is requested at line 11 to write a response content type

12: PrintWriter out = res.getWriter();

[API 2.0] ServletResponse.getWriter() is a new feature of JSDK version 2.0. If your Servlet engine does not
support JSDK 2.0 you can replace the above line by "ServletOutputStream out = res.getOutputStream();".
This change can be made in most of the example Servlets in this tutorial. The advantages of using
ServletResponse.getWriter() are discussed in section 4.4.
In lines 13 and 14 we use the PrintWriter to write the text of type text/html (as specified through the
content type).

13: out.println("<HTML><HEAD><TITLE>Hello World!</TITLE>"+

14: "</HEAD><BODY>Hello World!</BODY></HTML>");

The PrintWriter is closed, when the writing to it is finished.

15: out.close();

This line is included for completeness. It is not strictly necessary. The Web Server closes the PrintWriter
or ServletOutputStream automatically when a service call returns. An explicit call to close() is useful when
you want to do some post processing after the response to the client has been fully written. Calling
close() tells the Web Server that the response is finished and the connection to the client may be closed
as well.

In lines 18 through 21 we override the getServletInfo() method which is supposed to return information
about the Servlet, e.g. the Servlet name, version, author and copyright notice. This is not required for the
function of the HelloClientServlet but can provide valuable information to the user of a Servlet who sees
the returned text in the administration tool of the Web Server.

18: public String getServletInfo()

19: {

20: return "Your first Hello Servlet!";

21: }

2
The method being called depends on the kind of request (doGet, doPost, doPut).

The method normally receives the request and response objects, we then call the
.getWriter() method for the response obj that gets us the stream on which we can write our
output.

response.getWriter() returns a PrintWriter object that can send character text to the client.

You might also like