Wednesday, 13 July 2016

Servlet and JSP Q&A - Part 1

Hello everybody!

I have been working on Servlets and Jsp recently. I have developed a few projects to get familiar with these subjects. While working on my projects, I read quite a few books, watched videos and often had some search on forums to understand what I have been doing better and also to find some answers to my questions. As a result, I now have good(but not perfect of course) knowledge base related to Servlet and Jsp. So I thought creating a Q&A post about Servlet and Jsp would be very useful to keep this information on record and also to help those who are trying to get a little bit more into these subjects. So I hope you benefit from this post too!



Q1)What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods(HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
Q2)What does the container do?
Basically the container manages and runs the servlet. Webserver uses "Servlet Container" to load and run Servlets which supplies dynamic content. An example to the servlet container is Apache Tomcat. Container handles all threading, security and networking issues. The container creates a request and response object that servlets can use to get information about the request and send information to the client. It provides;
- Communication Support: provides an easy way for your servlets to talk to the web server.
- Lifecycle Management: controls the life and death of your servlets.
- Multithreading Support: automatically creates a new Java thread for every servlet request it receives.
- Declarative Security: let you use an XML deployment descriptor to configure security without having to hard-code it into your servlet.
- JSP Support: translates JSP codes into real Java.
Q3)What are the differences between doGet() and doPost() methods?
-In doGet(), the parameters are visible in the address bar, they are appended to the URL. In doPost(), parametres are not visible in the address bar.
-GET does not have a body. So parameters you can send are limited in the Request Line. You can maximum transfer 1024 characters through GET request. POST has a body that you can put parameters. doPost() does not have any limitations.
-doGet() is not good for sensitive data as the parameters do not get encrypted. In doPost() the parameters are encrypted which is more secure.
-doGet() allows user to bookmark the resource. doPost() does not allow this.
-doGet() is faster than doPost().
Q4)Explain a servlet life cycle.
-Load Servlet class:web container loads the servlet class mentioned in web.xml file.
-Create Servlet instance: one or more instance/object of servlet class is created.
-Call the init() method/Initialisaiton:the web container invokes init() method of the servlet instance. The init() method is called only one in the servlet life cycle.
-Call the service() method/servicing the request:the web container invokes the service() method to allow a servlet to process a client request. The service() method processes the request and returns the response back to the web container. The servlet then waits to receive and process subsequent requests.
-Destroy: the web container calls destroy() method before removing the Servlet instance from the service. The destroy() methodfree up the servlet instance so that it can be garbage collected. The destroy() method is invoked only once in a servlet life cycle.
Q5)Why do we use Servlets?
-To store and process the input data submitted by user from the screen by an HTML form.
-To generate and return the dynamic response to the user based on the request.
-To improve the system performance by handling multiple requests simultaneously which gives us high performing applications.
-To interact with database based on the user request with an ideal programming language.
-To manage state information in stateless HTTP. Because HTTP is a stateless (or non-persistent) protocol. Each request is treated by its own. A request will not know what was done in the previous requests.So we can use Servlets to store state information for performing the following processes.
Q6)What are the different techniques used in Session tracking? Explain each briefly.
-Cookies: are text files that keep some information and are stored on the client computer.
-Hidden Form Field: <input type="hidden" name="uname" value="Selen">
-URL Rewriting: we append a token or identifier to the URL of the next Servlet or the next resource.
-Http Sessions: container creates a session id for each user. The container uses this id to identify the particular user.
Q7)How does cookie work?Explain the types of cookies in servlet. How do we use them?
By default, each request is considered as a new request. Using cookies, we add cookie with response from the servlet and that cookie is stored in the cache of the client's browser. After that when request is sent by the same user, cookie is added with request by default. So we know that user is not a new user. 
There are 2 types of cookies in servlets.
-Non-persistent:only valid for single session. It is removed each time when user closes the browser.
-Persistent: valid for multiple session. It is removed only when user logout or signout. 
To create a cookie:
Cookie ck = new Cookie("user","selen");
response.addCookie(ck);
To delete a cookie:
Cookie ck = new Cookie("user","");
ck.setMaxAge(0);
response.addCookie(ck);
To get a cookie:
Cookie ck[] = request.getCookie();
for(int i=0; i<ck.length; i++){
out.print(ck[i].getName() + " " + c[i]k.getValue());
}
Q8)Why are some advantages and disadvantages of using cookies for session tracking?
Advantages:
-It is simple to maintain the state. Cookies are usually persistent, so for low-security sites, user data that needs to be stored long-term(such as user id) can be maintained easily.
-Cookies are maintained at the client side.
-Instead o just the session ID, the entire session data can be kept in the cookie for small to medium sized session data. 
Disadvantages:
-Only textual information can be set in cookie object whereas you can store complex data types (e.g. objects) in a session.
-Cookies only work for HTTP protocol.
-Cookies are stored on client-side. So if the cookies get corrupt, purged or expire or the client browser clears or disables the cookies, the information won't be avaliable.
Q9)What are the annotations used in Servlet 3?
Basically there are 3 annotations used for the Servlet. @WebServlet: for servlet class, @WebListener: for listener class, @WebFilter: for filter class.
Q10)Why do we use filters in Servlet?
We use filters for security checks, modifying the request or response, data compression, logging and auditing, response compression.
Q11)Explain an intercepting filter?
It intercepts the request from a client before the request reaches the Servlet and modifies the request if required. It intercepts the response from the Servlet back to the client and modifies if required. There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.

Q12)What is servlet lazy loading? What is preinitialisation of a servlet?
The Servlets are not initialised by the container from the start. It happens when the Servlet is requested for the first time. This is called lazy loading. By specifying <load-on-startup> element for a Servlet we can avoid lazy loading. The <load-on-startup> element of a deployment descriptor is used to load a Servlet file when the server starts instead of waiting for the first request. The process of loading a servlet before any request comes in is called preloading or preinitialising a servlet.
Q13)Why do we need constructor in servlet even though we have a init() method?
init() method is used for initialising the servlet however constructor is required in order to instantiate the Servlet class.
Q14)Why servlet is better than CGI?
Common Gateway Interface (CGI) is a standard way for web servers to interface with executable programs installed on a server that generate web pages dynamically. Servlet is better than CGI because:
-Servlet responses faster than CGI because it uses the multithreading concept. CGI performance is not that good as it creates a new object for each request whereas servlet allots a new thread for each request.
-Learning and implementing servlet is easier compared to CGI.
-Memory consumption is low in servlet compared to CGI.
Q15)How can you get the information about one servlet context in another servlet?
In context object we can set the attribute which we want to get in another servlet. (Context.setAttribute("name","value")) 
We can get that attribute using their name on another servlet. (Context.getAttribute("name"))
Q16)What is servlet chaining?
It is a method in which the output of one Servlet is the input of the next Servlet. It is the last Servlet in the chain that provides the output to the web browser.
To view the second part of the Q&A post, go over here.

Hope to see you in the next blog post.

Selen

No comments:

Post a Comment