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

SERVLETS

1. Servlets are simple JAVA Programs that run on the server and has the capability of handling
requests and generating dynamic response.

2. Basic Working overview of the servlet:

(a) The client (google chrome, firefox, etc.) first sends a request to the server (suppose we want to
access the website www.onlyjavatech.com)
(b) The servlet (the java program residing on the server) accepts this request from the client and
executes the tasks which can include various processing, or fetching data from database using jdbc,
etc.
(c) Once the server completes its task it generates a dynamic response in the form of HTML and
sends this response to the client which primarily fetches the home page of the website
www.onlyjavatech.com

3. We create a servlet(it is a simple JAVA Program which will be created inheriting an interface) using
the interface javax.servlet.Servlet. This interface has 5 methods out of which we will use 3 of them to
create a servlet program of our own.

The various methods present in this interface are as follows:

(a) public abstract void init (javax.servlet.ServletConfig); --> used to create and initialise the servlet
object
(b) public ServletConfig getServletConfig();
(c) public void service (javax.servlet.ServletRequest, javax.servlet.ServletResponse) throws
ServletException, IOException; --> used to perform the task that the servlet has to do
(d) public abstract java.lang.String getServletInfo();
(e) public abstract void destroy(); --> finishes the servlet program when all the tasks are done

4. Once we create this servlet program using the above methods and providing implementation for
the same example:

class MyServlet implements Servlet


{
//Override all the methods of the Servlet Interface
}

after this we need to provide a mapping in the web.xml(which is known as the Deployment
Descriptor) for executing the Servlet program without this xml configuration we would not be able to
run the servlet

Web.xml looks similar to this for mapping:

<servlet>
<servlet-name></servlet-name>
<servlet-class></servlet-class>
</servlet>

<servlet-mapping>
<servlet-name></servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
4. The second way to create a servlet program is by extending the class GenericServlet which prompts
us to provide the implementation of only one method:

public void service (javax.servlet.ServletRequest, javax.servlet.ServletResponse) throws


ServletException, IOException;

The other 4 methods default implementation is already provided in the class itself.

Class MyServlet extends GenericServlet


{
//override only service() method
Public void service (ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
//provide the body of the method
}
}

5. There is also a third way to create the servlet. If suppose we want to do some protocol specific
tasks using doGet(), doPost(), doPut(), etc. Then we can create the servlet by extending the
HttpServlet class.

Example:

class MyServlet extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println(“Welcome to my servlet !!”);
}
}

6. Servlet lifecycle in short is:


init() ---> service() ---> destroy()

The web container contains the servlet programs stored on the server. So when the client sends the
request to the server, the web container maps the request with the servlet in the web.xml file.

It then creates the request and response object for the client request.

Then calls the service method which does all the required processing.

After sending the response to the client, the web container destroys the servlet and deletes the
request and response objects.

7. We can fetch data from an HTML Form by using the servlet.


(a) We create the form using HTML
(b) We submit the form along with the filled in data in a servlet program (say: RegisterServlet.java)
(c) Inside the RegisterServlet we have the form data inside the request object, we can fetch this form
data using the HttpServletRequest object’s getParameter() method.
Example, suppose we get “name” and “password” from the form so we are going to fetch these by
the following:

request.getParameter(“name”);
request.getparameter(“password”);

8. Welcome file -> This is the file which the server will first open if there is no particular URL specified
while requesting. Suppose we want “home.html” to be the first page to open while opening a
particular website, so we have to configure the following in the web.xml:

<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>

9. Request Dispatcher is used to redirect (forward or include content) the response to another page.
Suppose after submitting the form we want to forward the response to another servlet/html/jsp page
named as RegisterServlet.html, so in this case we have to write the following:

RequestDispatcher rqd = request.getRequestDispatcher(“RegisterServlet.html”);


rqd.forward(request, response);

So here the request will be forwarded to “RegisterServlet.html” after the form submission.

Similary, there is another use of the Request Dispatcher, if one wants to include the data of the
reponse of a particular html/jsp/servlet, we have to use the include() method functionality of the
request dispatcher.

Example: Suppose we want to include the content of “index.html” after a particular proceeding, for
that we have to do the following:

RequestDispatcher rqd = request.getRequestDispatcher(“index.html”);


rqd.include(request, response);

10. Internal Working of the servlet:

(a) The client(chrome, firefox, etc) first sends an HTTP Request to the web server(Apache Tomcat) , an
HTTP Servlet request is submitted to any particular servlet.

(b) The web server upon receiving a request, creates an object of that particular servlet class (or we
can say the server instantiates the servlet class).

(c) Once the servlet object is created, the web server now creates the ServletConfig object and then
initiates a call to the default init() method of the GenericServlet class by passing the servlet config
object:- public void init(ServletConfig config). Thus on calling the init() method indicates that the
servlet lifecycle has just started.

(d) Now the web server will call the HttpServlet class’ service() method on the servlet object. Since
the servlet object does not have its own service method, so the web server will call the
doPost()/doGet()/doPut(), etc. Methods of the HttpServlet class and thus the overridden methods of
the servlet object will get called.
11. Deployment Descriptor is the web.xml which is the file that contains the configuration of our web
application. This is a very important file. It resides in the WEB-INF Folder.

12. Parameters -> The values which are set directly by user are called parameters. Suppose the user
passes two values in the form n1 and n2. So n1 and n2 are parameters.
The way of fetching parameters:

String name = request.getParameter(“name_of_the_parameter”);

13. Attributes -> The values which are not provided directly bu user, but the one which servlet can set
and get are attributes. Servlets can modify, add or remove attributes but can never modify or remove
parameters. Suppose n1 and n2 are passed by user are parameters, but summation of the two, I.e.
sum = n1+n2, here sum is the attribute as we can set “sum” as the attribute in the servlet itself. The
way to fetch attributes are:

request.setAttribute(String name, Object value)


Object value = request.getAttribute(String name)
request.removeAttribute(String name)

14. Managing session by Cookies (watch the explanation given by Durgesh Tiwari in his youtube
content):

Cookie is the child class of javax.servlet.http


Cookies store values in the form of (key,value) pair
When user sends request to the server for the first time, we should add the information using cookies
and send it along with the response.

String name = request.getParameter(“name”);


Cookie cookie = new Cookie(“user_name”,name);
response.addCookie(cookie);

Then when the same user again sends request for the second time, this time the cookies is again send
along with the request so that server can know that it’s the same person that has requested the
content.

Cookie[] cookies = request.getCookies(); // when we fetch cookies from request, we get multiple
cookies so we store them in an array of “Cookie”
15. Managing session using URL Rewriting concept: Basically after the first request, when the same
user sends a second request we have to append the request data in the url itself.

Example: if from the first request we are fetching the below date:
String user_name = request.getParameter(“name”);

During the second call we will append this data in the url itself to forward it to the second servlet
calling:

out.println(<a href=’servlet2?user=”+user_name”’> Go to second servlet </a>);


Here we are appending the data of “user_name” in the variable “user” and appending the same to
the url of the second servlet.

(for better understanding you can refer to Durgesh Tiwari youtube channel)

16. Session Tracking using HttpSession interface. We can store data within the session object and the
data will be available as long as the session is active. Session is deactivated only when the browser is
closed, or we manually deactivate it.

The two most important methods that we use from the HttpSession are:
setAttribute(“key”, “value”)
getAttribute(“key”)
getId() --> gives the id of the current session
removeAttribute(“key”)
invalidate() --> to invalidate the current session

How do we get the session object?


HttpSession session = request.getSession();

Then on this “session” variable we can use the above mentioned session methods

************************************ COMPLETED ************************************

You might also like