You are on page 1of 14

Chapter-3

Q1. Explain servlet life cycle with example to demonstrate every


state (page 259)
Ans.
Servlets follow a life cycle that governs the multithreaded environment in
which the servlets run. It also provides a clear perception about some of
the mechanisms available to the developer to share server side resource.
1.The first phase of the servlet life cycle is initialization.
Init() method is called when a servlet is created for the first time. It is not
called again for other user requests. It is only used only for one time
initializations.
A servlet is normally created when a user invokes a URL corresponding to
servlet, for the first time.
Public void init() throws ServletException
{
// Initialization code
}
2.The second phase of a servlet life cycle is the service phase. Each time
a server receives a request for a servlet, the server, the server spawns a
new thread by reusing an idle thread from a thread pool.
The service() method verifies the HTTP request type
(GET,POST,PUT,DELETE) and accordingly calls the doGet(), doPost(),
doPut(), doDelete() methods.
<html>
<form name=greetForm method=post>
@Override
Public void doGet (HttpServletRequest request, ahttpServletResponse
response) throws ServletException, IOException
{
//Servlet code
}
@Override
Public void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
doGet(request,response);
}
3.The destruction phase is third phase and final phase of servlet life
The destroy() method runs only once during the lifetime of a servlet, and
signals the end of the servlet instance. A servlet container holds a servlet
instance till the servlet is active or its destroy() method is called.
Public void destroy()

Q2. What is deployment descriptor? Explain it with an example of


web.xml ()
Ans.
*Java web applications use a deployment descriptor file to determine how
URLs map to servlets, which URLs require authentication and other
information.
*This file is named web.xml, and resides in the WEB-INF folder of the
application
*A web application's deployment descriptor describes the classes,
resources and configuration of the application and how the web server
uses them to serve web requests.
*When the web server receives a request for the application, it uses the
deployment descriptor to map the URL of the request to the code that
ought to handle the request.
*Example :
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<servlet>
<servlet-name>comingsoon</servlet-name>
<servlet-class>mysite.server.ComingSoonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>comingsoon</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
*Deployment descriptors defines mapping between URL paths and the
servlets that handle requests with those paths.
*The web server uses this configuration to identify the servlet to handle
the given request method and call the class method corresponding to that
request. (doGET or doPOST)
*To map a URL to a servlet, <servlet>..</servlet> tags are used and then
define the mapping by using <servlet-mapping></servlet-mapping>
element.
*The <servlet> element declares the servlet, including a name used to
refer to servlets to other elements in the file, the class to use for the
servlet, and initializing paramenters.
*The name of each servlet should be unique across the deployment
descriptor.
Q3. Develop any servlet application that demonstrates use of
session management using HttpSession interface
Ans.

import
import
import
import
import
import
import
import

java.io.IOException;
java.io.PrintWriter;
java.util.Date;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
javax.servlet.http.HttpSession;

public class MySessionServlet extends HttpServlet {


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Retrive the session object for the current user session
// A new session is created if a session object has not been vreated
previously...
try (PrintWriter out = response.getWriter()) {
HttpSession sessionobj = request.getSession(true);
// Create and update the variable that holds the count indicating
the number of times the page
// has been accessed by the current session user.
Integer count = (Integer) sessionobj.getAttribute("count");
if(count==null) count = new Integer(1);
else count =new Integer(count.intValue()+1);
// Save the updated count value to the current user session
sessionobj.setAttribute("count",count);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head> <title> Displaying the session information of
the current user</title></head>");
out.println("<body>");
out.println("<h1> Displaying the details of current user
session</h1>");
out.println("<h2>You have visited this page "+count+" times
</h2>");
// The first part : display summary of request data
out.println("<h3> Displaying summary of request data </h3>");
out.println("Session ID in request object:
"+request.getRequestedSessionId()+"<br>");
out.println("Is session ID in request from a
cookie:"+request.isRequestedSessionIdFromCookie()+"<br> ");
out.println("Is session ID in the request from the URL:
"+request.isRequestedSessionIdFromURL()+"<br> ");
out.println("Is Requested Session ID valid:
"+request.isRequestedSessionIdValid()+"<br><br><br>");
out.println("<h3> Displaying summary of session data </h3>");

out.println("Is it a new session: "+sessionobj.isNew()+"<br>");


out.println("Session ID:"+sessionobj.getId()+"<br> ");
out.println("Session Creation time:"+new
Date(sessionobj.getCreationTime())+"<br> ");
out.println("Time at which the last session was accessed:"+new
Date(sessionobj.getLastAccessedTime())+"<br> ");
out.println("</body>");
out.println("</html");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.
Click on the + sign on the left to edit the code.">
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}

Q5. What are cookies? Write a servlet to demonstrate the use of cookies.
(page 291)
Ans.
When a session is created, the container sends the cookie with
session identifier to the client.
Some other useful information, such as surname and password is
also sent with the cookies, less than 4kb.
The cookie names JSESSIONID, is sent by the container as a
response in the HTTP response header.
Then, whenever any subsequent request is received from the same
web client session (assuming the client supports cookies), the
cookie is sent back by the client to the server as part of the request.
In this case, the cookie value is used by the server to look for the
session state information to be passed to the servlet.
Finally, in the subsequent responses, server sends the updated
cookie back to the client.
As the container handles the process of sending a cookie, the
servlet code is not required while using the cookie. A web browser
automatically handles the process of sending cookies back to the
server unless the client disables the cookies.
Cookie is used by the server to maintain a session.
Example:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Cookie[] coki = request.getCookies();
Cookie tokencookie = null;
if(coki!=null)
{
for(int i=0;i<coki.length;i++)
{
if(coki[i].getName().equals("token"))
{

tokencookie = coki[i];
break;
}
}
}
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Extracting the token cookie </title>");
out.println("</head>");
out.println("<body>");
out.println("style=\"font-family:arial;font-size:12pt\">");
String resetParam = request.getParameter("resetParam");
if(tokencookie==null || (resetParam!=null &&
resetParam.equals("yes")) )
{
Random rnd = new Random();
long cookieid = rnd.nextLong();
out.println("<p>Welcome. A new tone "+cookieid+" is now
established</p>");
tokencookie= new Cookie("token",Long.toString(cookieid));
tokencookie.setComment("A cookie named token to identify
user");
tokencookie.setMaxAge(-1);
tokencookie.setPath("/HandleSession/CookieServlet");
response.addCookie(tokencookie);
}
else
{
out.println("Welcome back.... your token is
"+tokencookie.getValue()+"</p> ");
}
String requestURLSame = request.getRequestURL().toString();
String requestURLNew = request.getRequestURL() + "?
resetParam=yes";
out.println("<p>Click <a href="+requestURLSame+"> here
</a> to continue browsing with same identity </p> ");
out.println("<p> Otherwise, click <a
href="+requestURLNew+"> here </a> to browse with new identity
</p>");
out.println("</body>");
out.println("</html>");
}
}
@Override

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
Q10. What is ServletContext and ServletConfig object? Explain with
example. Differentiate between the ServletContext and ServletConfig
Object. (pg 271)
Ans:
Servlet context objects helps to provide context information in a servlet
container.
A servletcontext object is used to communicate with the servlet
container while the servletconfig is passed to the servlet by the
container when the servlet is initialized.
A servlet config object contains a servletcontext object, which specifies
the parameters of a particular servlet while the servletcontext object
specifies the parameters for an entire web application.
The servletcontext object parameters are available to all the other
servlets in the application.
Q11. Explain use of requestdispatcher interface with an example.
Ans
Methods of RequestDispatcher
RequestDispatcher interface provides two important methods
Methods

Description

void forward(ServletRequest request,

forwards a request from a servlet to another


resource (servlet, JSP file, or HTML file) on
the server

ServletResponse response)

void include(ServletRequest request,

includes the content of a resource (servlet,

ServletResponse response)

JSP page, HTML file) in the response

How to get an Object of RequestDispatcher


getRequestDispatcher() method of ServletRequest returns the object
of RequestDispatcher.
RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.forward(request,response);

OR
RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.include(request,response);
index.html
<form method="post" action="Validate">
Name:<input type="text" name="user" /><br/>
Password:<input type="password" name="pass" ><br/>
<input type="submit" value="submit">
</form>
Validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)

throws ServletException, IOException {


response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String name = request.getParameter("user");
String password = request.getParameter("pass");
if(password.equals("studytonight"))
{
RequestDispatcher rd =
request.getRequestDispatcher("Welcome");
rd.forward(request, response);
}
else
{
out.println("<font color='red'><b>You have entered incorrect
password</b></font>");
RequestDispatcher rd =
request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}finally {
out.close();
}
}
}
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<h2>Welcome user</h2>");
} finally {
out.close();
}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Validate</servlet-name>

<servlet-class>Validate</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
This will be the first screen. You can enter your Username and Password
here.

When you click on Submit, Password will be validated, if it is not


'studytonight' , error message will be displayed.

Enter any Username, but enter 'studytonight' as password.

Password will be successfully validated and you will be directed to the


Welcome Servlet.

12. Explain Servlet by using annotation interface with example.


(Page 270, whole page)
15. Role of web container.
Ans.
What is Web Container in Java?
Web Container is a java application that controls servlet. Servlet do not
have a main() method, So they require a container to load
them. Container is a place where servlet gets deployed.
When a client sends a request to web server that contain a servlet,
server sends that request to container rather than to servlet directly.
Container then finds out the requested servlet and pass the Http
Request and response to servlet and loads the servlet methods i.e.
doGet() or do Post().
19. How can you pass the parameters to a servlet? Explain with
example.
Ans.
Heres a serlvet code example to demonstrate how to pass a parameter to a servlet
by using ServletConfig init-param in web.xml
In the deployment descriptor (web.xml)
Put your parameter value in init-param and make sure inside the servlet element

<servlet>
<servlet-name>ServletName</servlet-name>
<servlet-class>com.mkyong.ServletDemo</servlet-class>

<init-param>
<param-name>email</param-name>
<param-value>admin@email.com</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>ServletName</servlet-name>
<url-pattern>/Demo</url-pattern>
</servlet-mapping>

Servlet code
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws IOException{

PrintWriter pw = response.getWriter();
pw.println(getServletConfig().getInitParameter("email"));

The getServletConfig().getInitParameter(email) method is use to get the


ServletConfig parameter value in web.xml. Btw, this parameter only available for this
servlet only. If you want a parameter which allow globally access by whole web
application, you need put the parameter in servlet context element.

You might also like