What is Servlet?
A Servlet is a Java class that runs within a web container in an application server, servicing multiple client requests concurrently forwarded through the server and the web container. The web browser establishes a socket connection to the host server in the URL, and sends the HTTP request. Servlets can forward requests to other servers and servlets and can also be used to balance load among several servers.
CRMServlet.java
package com.devx;
//import statements
public class CRMServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
ServletOutputStream out = res.getOutputStream();
out.setContentType(“text/html”);
out.println("<html><h1>Output to Browser</h1>");
out.println("<body>Written as html from a Servlet<body></html>");
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doPost(req, res);
}
}
Deploment descriptor
WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<servlet>
<servlet-name>CRMServlet</servlet-name>
<servlet-class>com.devx.CRMServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CRMServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
What is the difference between HttpServlet and GenericServlet?
Both these classes are abstract but:
GenericServlet | HttpServlet |
A GenericServlet has a service() method to handle requests. | The HttpServlet extends GenericServlet and adds support for HTTP protocol based methods like doGet(), doPost(), doHead() etc. All client requests are handled through the service() method. The service method dispatches the request to an appropriate method like doGet(), doPost() etc to handle that request. HttpServlet also has methods like doHead(), doPut(), doOptions(), doDelete(), and doTrace(). |
Protocol independent. GenericServlet is for servlets that might not use HTTP (for example FTP service). | Protocol dependent (i.e. HTTP). |
Q Explain the life cycle methods of a servlet? FAQ
A: The Web container is responsible for managing the servlet’s life cycle.The Web container creates an instance of the servlet and then the container calls the init() method. At the completion of the init() method the servlet is in
ready state to service requests from clients. The container calls the servlet’s service() method for handling each request by spawning a new thread for each request from the Web container’s thread pool [It is also possible to
have a single threaded Servlet]. Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.
Note: - HttpServlet's service() method parses the client request and forwards the client request to the appropriate HTTP method. For example, if an HTTP GET request comes into service(), service() preprocesses the GET request and then forwards it to doGet().
How do you handle both HTTP GET and POST requests in the same servlet?
Implement doGet() in your servlet and in your doPost() method, forward the call to doGet():
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
doGet(req, res);
}
Implement doGet() in your servlet and in your doPost() method, forward the call to doGet():
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
doGet(req, res);
}
What is the difference between doGet () and doPost () or GET and POST?
A 13: Prefer using doPost() because it is secured and it can send much more information to the server.
GET or doGet() | POST or doPost() |
The request parameters are transmitted as a query string appended to the request. All the parameters get appended to the URL in the address bar. Allows browser bookmarks but not appropriate for transmitting private or sensitive information. http://MyServer/MyServlet?name=paul This is a security risk. In an HTML you can specify as follows: <form name=”SSS” method=”GET” > | The request parameters are passed with the body of the request. More secured. In HTML you can specify as follows: <form name=”SSS” method=”POST” > |
doGet() method passes data through Request Header. | Where as doPost() method passes data through message body. |
GET is not appropriate when large amounts of input data are being transferred. Limited to 1024 characters. | But in case of doPost() is passes unlimited length of data. |
doGet() method passes textual data. | Where as doPost() method passes textual data as well as binary data such as serialized Java objects. |
Q. If you want a servlet to take the same action for both GET and POST request, what would you do?
You should have doGet call doPost, or vice versa.
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
ServletOutputStream out = resp.getOutputStream();
out.setContentType(“text/html”);
out.println("<html><h1>Output to Browser</h1>");
out.println("<body>Written as html from a Servlet<body></html>");
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
doPost(req, resp); //call doPost() for flow control logic.
}
Q : What is pre-initialization of a Servlet?
A: By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading. The servlet deployment descriptor
(web.xml) defines the <load-on-startup> element, which can be configured to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called pre-loading or pre-initializing a servlet. We can also specify the order in which the servlets are initialized.
<load-on-startup>2</load-on-startup>
Q 14: What are the ServletContext and ServletConfig objects? What are Servlet environment objects?
A: The Servlet Engine uses both interfaces. The servlet engine implements the ServletConfig interface in order to pass configuration details from the deployment descriptor (web.xml) to a servlet via its init() method.
public class CRMServlet extends HttpServlet {
//initializes the servlet
public void init(ServletConfig config)throws ServletException {
super.init(config);
}
…
}
ServletConfig | ServletContext |
The ServletConfig parameters are for a particular Servlet. The parameters are specified in the web.xml (i.e. deployment descriptor). It is created after a servlet is instantiated and it is used to pass initialization information to the servlet. | The ServletContext parameters are specified for the entire Web application. The parameters are specified in the web.xml (i.e. deployment descriptor). Servlet context is common to all Servlets. So all Servlets share information through ServletContext. |
String strCfgPath = getServletConfig().getInitParameter("config"); String strServletName = getServletConfig().getServletName(); | String strClassName = getServletContext(). getAttribute("GlobalClassName"); |
What is the need of super.init(config) in servlets?
Super.init(config) in servlet - to get servelt context.
What is a RequestDispatcher? What object do you use to forward a request?
A: A Servlet can obtain its RequestDispatcher object from its ServletContext.
//…inside the doGet() method
RequestDispatcher rd = request.getRequestDispatcher(“nextServlet”);
//relative path of the resource
or
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(“/nextServlet”);//absolute path of the resource
//forwards the control to another servlet or JSP to generate response.
//This method allows one servlet to do preliminary processing of a request //and another resource to generate the response.
rd.forward(request,response);
// or includes the content of the resource such as Servlet, JSP, HTML, Images //etc into the calling Servlet’s response.
rd.include(request, response);
What is the difference between the getRequestDispatcher(String path) method of “ServletRequest” interface and “ServletContext “ interface?
Javax.sevlet.ServletRequest getRequestDispatcher(String Path) | Javax.servlet. ServletContext getRequestDispatcher(String Path) |
In order to create request. getRequestDispatcher (String Path) We need to give the relative path of the resource | In order to create getServletContext(). getRequestDispatcher (String Path) We need to give the absolute path of the resource. |
Relative path is a path, it is considered “relative to the original request”. | Absolute path is a path,the container sees that as “String from the root of the Web Application” |
In case of the absolute path, path name should be begin with a forward slash (“/”). |
Q: What is the difference between forwarding a request and redirecting a request?
A: Both methods send you to a new resource like Servlet, JSP etc.
forward | redirecting-sendRedirect |
Forward action takes place within the server without the knowledge of the browser. Accepts relative path to the servlet or context root. | Sends a header back to the browser, which contains the name of the resource to be redirected to. The browser will make a fresh request from this header information. Need to provide absolute URL path. |
A forward happens on the server side with same request and response object. | While sendRedirecr happens on the client side with new request and response object. |
There will be a scope hold on the forward. | But Scope destroyed in case of sendRedirect. |
A forward hands the request to another resource on the server, usually within the same Web application. | But a sendRedirecr simply tells the browser to go a different URL, may be in same or in different web application. |
No extra network trip. | Though extra round trip in the sendRedirect () method is slower than forward (), sendRedirect () is more flexiable than forward () because it can redirect the user to any URL, while forward () works only within the same web application. |
response.sendRedirect(“/nextServlet”); | RequestDispatcher rd = request.getRequestDispatcher(“nextServlet”); rd.forward(request,response); |
Q. What is the difference between request parameters and request attributes?
Request Parametes | Requset attributes |
Parameters are form data that are sent in the request from the HTML page. These parameters are generally form fields in an HTML form like: <input type=”text” name=”param1” /> <input type=”text” name=”param2” /> Form data can be attached to the end of the URL as shown below for GET requests http://MyServer:8080/MyServlet? param1=Peter¶m2=Smith or sent to the sever in the request body for POST requests. Sensitive form data should be sent as a POST request. | Once a servlet gets a request, it can add additional attributes, then forward the request off to other servlets or JSPs for processing. Servlets and JSPs can communicate with each other by setting and getting attributes. request.setAttribute(“calc-value”, new Float(7.0)); request.getAttribute(“calc-value”); |
Return type is String. | Return type is Object. |
You can get them but cannot set them. request.getParameter("param1"); request.getParameterNames(); | You can both set the attribute and get the attribute. You can also get and set the attributes in session and application scopes. request.setAttribute(String name, Object Value); request.getAttribute(String name); |
What is Session Tracking?
A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications
the default time-out value for session variable is 20 minutes, which can be changed as per the requirement.
The “http protocol” is a stateless request/response based protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time.
Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions(HttpSession)
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions(HttpSession)
What is HTTPSession Class?
HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.
HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable. In a Java servlet the session can be obtained as follows :
HttpSession session = request.getSession(true); //returns a current session or a new session
//To put/get a value in/from the session
Name name = new Name(“Peter”);
session.setAttribute(“Firstname”, name); //session.putValue(…) is deprecated as of 2.2
session.getAttribute(“Firstname”);//get a value. session.getValue(…) is deprecated
//If a session is no longer required e.g. user has logged out, etc then it can be invalidated.
session.invalidate()
//you can also set the session inactivity lease period on a per session basis
session.setMaxInactiveInterval(300);//resets inactivity period for this session as 5 minutes