If you are all set to attend an interview related to J2EE/Java Web application development then, it is recommended to brush up this important concept.I witnessed this question in telephonic round interview. Today I am documenting it for future reference and for others.
What is Servlet ?: A Servlet is a Java program that runs within a servlet container. Servlets receive and respond to requests from Web clients. Servlets could in principle communicate over any client–server protocol, but they are most often used with the HTTP protocol. Thus "servlet" is often used as shorthand for "HTTP servlet". As every object is having a life-cycle so as of servlet instance.
The life-cycle of a servlet is controlled by the container in which the servlet has been deployed. Life cycle of servlet can be broadly divided into three stages :
1. Initialization stage -
2. Service stage - service() - For each request
3. Destroy stage. - destroy() - Executed only once
We can represent all three method executing in servlet container as follows :
Diagram taken from : http://www3.ntu.edu.sg/
1. Initialization phase : In this stage web-container initializes the servlet instance by calling the init() method and ONE instance per JVM for each servlet is created. It is important to note that init() method can be invoked in either of two ways :
1. On demand basis - On arrival of first HTTP request for the given servlet .
2. On Servlet container start: - When servlet container start,it reads the web.xml ,finds the declared servlets in the classpath and if <load-on-startup> is configured with an integer value 0 or more then for the given servlet one instance of that servlet will be created and are stored in memory and reused every time the request arrives. (Always remember REUSED !!).Sample code for servlet config of load-on-startup:
Notes :
Refer J2EE developer interview questions
======================End of article=====================
What is Servlet ?: A Servlet is a Java program that runs within a servlet container. Servlets receive and respond to requests from Web clients. Servlets could in principle communicate over any client–server protocol, but they are most often used with the HTTP protocol. Thus "servlet" is often used as shorthand for "HTTP servlet". As every object is having a life-cycle so as of servlet instance.
The life-cycle of a servlet is controlled by the container in which the servlet has been deployed. Life cycle of servlet can be broadly divided into three stages :
1. Initialization stage -
init() -
Executed only once2. Service stage - service() - For each request
3. Destroy stage. - destroy() - Executed only once
We can represent all three method executing in servlet container as follows :
Diagram taken from : http://www3.ntu.edu.sg/
1. Initialization phase : In this stage web-container initializes the servlet instance by calling the init() method and ONE instance per JVM for each servlet is created. It is important to note that init() method can be invoked in either of two ways :
1. On demand basis - On arrival of first HTTP request for the given servlet .
2. On Servlet container start: - When servlet container start,it reads the web.xml ,finds the declared servlets in the classpath and if <load-on-startup> is configured with an integer value 0 or more then for the given servlet one instance of that servlet will be created and are stored in memory and reused every time the request arrives. (Always remember REUSED !!).Sample code for servlet config of load-on-startup:
<servlet>
<servlet-name>controlServlet</servlet-name>
//Mapping details .....
<load-on-startup> 1 </load-on-startup>
</servlet>
Note : load-on-startup can specify an (optional) integer value. If the value is greater than 0, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers.
Note : load-on-startup can specify an (optional) integer value. If the value is greater than 0, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers.
Please note, init(ServletConfig) is being called by the servlet container to indicate a servlet that the servlet is being placed into service.We can override this init() method see this for reference.
public void init(ServletConfig config) throws ServletException
{
//some initialization - like getting database connection,
// resource management etc.
Notes :
- init() is not the entry point of a servlet. servlet constructor is executed before execution of init() but it is not recommended to use constructor for any Servlet. why? Find here
- The container would decide how many instances of servlet would be instantiated upfront to cater the requests.This is container implementation..(Confused !! But it's fact)
2. Service phase : In this stage for every new request a new thread is created or allocated from a pool to invoke that servlet instance which was created in earlier stage . The HttpRequest and HttpResponse objects will be new for each new request.
One commonly asked question in interview : How HTTP request coming from web client is served by servlet ?
One commonly asked question in interview : How HTTP request coming from web client is served by servlet ?
On request arrival web container(servlet container) calls service() method of servlet and the service() method determines the kind of request and calls the appropriate method (doGet() or doPost() for handling the request and sends response to the client using response object. Lets consider following code blocks:
public class SimpleHttpServlet extends HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("<html><body>GET response</body></html>"); } protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("GET/POST response"); } }HttpServlet(javax.servlet.http.HttpServle) class reads the HTTP request(coming from client), and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method.
Notes :
- It is important to note that each request is served by a new thread if and only if our servlet is not implementing SingleThreadModel interface. It is not recommended to use SingleThreadModel interface.
- Is servlet threadsafe ? Answer is : No, but we can make by it thread-safe by following some standard so that it can serve multiple request in thread safe manner. How we can make servlet thread safe?
Refer J2EE developer interview questions
======================End of article=====================
Wonderful ideas! You are providing the different kinds of content is very useful for me and I gain more details from your article. I am always following your blog and keep posting...
ReplyDeleteSpark Training in Chennai
Spark Training
Excel Training in Chennai
Corporate Training in Chennai
Embedded System Course Chennai
Linux Training in Chennai
Tableau Training in Chennai
Power BI Training in Chennai
Social Media Marketing Courses in Chennai
It is a great post. Keep sharing such kind of useful information.
ReplyDeleteEducation
Technology
This post is really useful and helpful to know more about the things which you have shared. I appreciate you for such a great amount of information. I assure this would be beneficial for many people. Best Advanced Java & Data Structures Course In Delhi
ReplyDeleteInformative blog! I am truly awed by this blog post! Very clear explanation about the full stack Development. I agree with all points.Hire Full Stack Developers
ReplyDeleteMua vé máy bay tại Aivivu, tham khảo
ReplyDeletegiá vé máy bay đi Mỹ khứ hồi
vé máy bay từ texas về việt nam
vé máy bay từ đức về sài gòn
vé máy bay từ nga về tphcm
khi nào có chuyến bay từ anh về việt nam
vé máy bay từ pháp về việt nam giá rẻ
danh sách khách sạn cách ly đà nẵng
Hey there
ReplyDeleteThanks for sharing this interesting post, Keep on sharing more like this
Software Development company
Mobile app development company
Best web development company
Infotech Softnet is the best C++ institute in Janakpuri and caters to the needs of all the students. With a team of highly experienced trainers and a proven track record of success, we have earned a reputation as the best C++ institute in the area. Our comprehensive C++ courses are designed to cater to the needs of both beginners and advanced learners. We provide practical, hands-on training that enables our students to master the language quickly and effectively. Our state-of-the-art facilities and advanced teaching methodologies make us stand out from other computer training institutes in Janakpuri.
ReplyDeleteJoin Infotech Softnet Computer Education today and unlock your potential in C++. Whether you are looking to kickstart your career in programming or simply enhance your skills, we have a course for you.
It is quite helpful that you have offered this information on your blog. We sincerely appreciate the effort you put into your article, and it helps us, too. Thank you for sharing this information.cms development
ReplyDeleteThe fact that you provided this knowledge on your blog is quite beneficial. We genuinely appreciate the time and work you put into writing your article, which also benefits us. I appreciate you giving this knowledge.web development services
ReplyDeleteYou have given me a very complete post about. I and those who like it think it's a fantastic piece. Your sharing of this information with us is greatly appreciated.electronic signature
ReplyDelete