Java Servlets FAQs


What is a servlet ?
Simply it means something that can extend a servers functionality.
(for example a servlet can be used to process DB queries or client request processing )

So servelts run in a server just like PHP and ASP.net and normally serverlets are deployed in a web container. So there can be many servlets in a web container.


What happens in a sevelts life cycle ?
3 Things actually.
  1. Init() - Container intialize a servlet. (Serveltconfig object is initially passed to this method)
  2. Service() - servlet handles the service. Decides doGET(),doPOST() or any appropriate method to execute. Normally servlet can handle any number of requests and each request run on a separate thread.
  3. Destroy() - Once the service is performed that servlet/thread instance is killed.
What describes the first view/page to load in a Java web application unless it is not configured in the web server ?
web.xml (deplyment descripter)in WebContent/WEB-INF

How a Java class becomes a servlet ?
Two things.
1. It should extend HttpServlet class (if the servelt is a type of HTTP coz there are other types of servelets as well which inherits from GenericServelt class)
2. it should contain proper annotations (or Servelt tags in web.xml for apps before JAVA 5)

What happens in a Servlet web project when the browser executes an URL ?

  1. Browser sends the url to Java server (Lets say www.example.com/webapplication1/randomservlet1 to wildfly/Jboss server or tomcat or anything)
  2. Jboss at example.com has multiple web applications. 
  3. Jboss get the url and sees that it belongs to webappplication 1
  4. Jboss creates 2 objects
    1. HttpServletRequest object - as inputs to servlet
    2. HttpServletResponse object -as outputs from servlets
  5. Jboss then sends these 2 objects to randomservlet1. (probably doGET() after reading web.xml)
  6. Then servelt does its job.
  7. If there is something to be sent back to browser it is included in the response object.
  8. Jboss renders what is in the response object and sends back to browser. 

How a servelt gets a value from url prameter from ?name=RobinHood
String name = response.getPrameter("name")
If it is a GET this will be executed in doGET()
If it is a POST this will be executed in doPOST()
If it is a HEAD this will be executed in doHAED() and so on...................

How object creation happens in Servlet application ?

  • HttpServletRequest, HttpServletResponse objects are created per connection (These are stateless)
  • Create HttpSession objects if we want to maintain the state (getSession() from request object per client/browser) 
  • Create ServletContext if you want to have persistand data across users/browser (setServeltContect() from request object)
  • HTTPServelt s are cerated in threads per connection




Share:

0 comments: