A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications. All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods.
Suppose user made the request for the URL <strong> www.google.com/intl/en/privacy.html </strong> then: <br/> <strong>1. </strong> web browser establishes a connection with www.google.com server by locating its IP address from a DNS server. <br/> <strong>2. </strong> The web browser then sends a request to the server to retrieve the intl/en/privcy.html file.<br/> <strong>3. </strong>The server respond with the info about the the requested HTML page and the contents of privacy.html file.<br/> This process of sending a request and receiving a response from the server is known as transaction.An HTTP session remains open till a single transaction is completed.
Performance of servlets is better than CGI scripts because CGI scripts need to be loaded in various process for every request. On the other hand, a servlet , once loaded in the memory, can be run multiple times on a single lightweight thread.
<strong>1.</strong> Web server converts the request into an HTTPServletRequest object.<br/> <strong>2.</strong> The HTTPServletRequest object is sent to a web compnent to establish a communication with javabeans components.<br/> <strong>3. </strong>The HTTPServletResponse object is generated by the web component and finally the HTTPServletResponse object displys the data to the client as the resonse generated by the web server.
The main functions of Servlet container are:<br/> <strong>1. Lifecycle management : </strong>Managing the lifecycle events of a servlet lik class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.<br/> <strong>2. Communication support : </strong>Handling the communication between servlet and Web server.<br/> <strong>3. Multithreading support : </strong>Automatically creating a new thread for every servlet request and finishing it when the Servlet service() method is over.<br/> <strong>4. Declarative security : </strong>Managing the security inside the XML deployment descriptor file.<br/> <strong>5. JSP support : </strong>Converting JSPs to servlets and maintaining them.
When a client request is received by a web container , firstly the container maps the request with an appropriate servlet according to deployment descriptor. After the servlet is idenified, the web container loads the servlet class and creates an instance of the servlet. The servlet is then initialized by calling init() method. After calling the init() method, the service() ethod passess the request and response object to the web conatainer. The web container invokes the destroy() method to remove the servlet, if the servlet is not required.
Yes, Servlet implementation classes can have constructor but there is no point in creating a constructor in servlet because Servlet require ServletConfig object for initialization which is created by container itself.
<strong>javax.servlet.Servlet </strong>is interface, it defines methods for all the implementations - that's what interfaces usually do.<br/> <strong>javax.servlet.GenericServlet </strong>is protocol independent. It is abstract, so it is not to be directly instantiated. It is usable class to extend if you some day have to write servlet for protocol other than HTTP.<br/> <strong>javax.servlet.http.HttpServlet</strong> is abstract class to be extended if you want to communicate over HTTP protocol. Most likely you only have to care about this one.
Deployment descriptor is a configuration file for the web application and it’s name is web.xml and it resides in WEB-INF directory. Servlet container use this file to configure web application servlets, servlet config params, context init params, filters, listeners, welcome pages and error handlers.<br/> With servlet 3.0 annotations, we can remove a lot of clutter from web.xml by configuring servlets, filters and listeners using annotations.
Based on the bussiness, we can have multiple servlets for specific business scenario. In that case it is required to have inter-servlet communication. We can achieve this in Servlet by using RequestDispatcher forward() and include() methods and provide additional attributes in request for other servlet use.
<strong>1.</strong> The first aim for a servlet is to achieve thread safety by virtue of no shared state. Any shared state will fail to be that when the servlet is deployed into a load-balancing cluster. <br/> <strong>2.</strong> Any local variables in service methods are thread safe because they are specific to each thread but for shared resource we can use synchronization to achieve thread safety in servlets.
<strong>1.</strong> RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a completely new request.<br/> <strong>2.</strong> forward() is handled internally by the container whereas sendRedirect() is handled by browser.<br/> <strong>3.</strong> We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.<br/> <strong>4.</strong> In forward() browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect() URL in address bar change to the forwarded resource.<br/> <strong>5.</strong> forward() can’t be used to invoke a servlet in another context, we can only use sendRedirect() in this case.
To have any useful behaviour, it is expected that you will have to override the methods. HttpServlet does not have useful functionality on its own.Making its constructors private would limit the ability for subclasses to be created.<br/> The design of HttpServlet was probably not ideal -- as on many pages, forms especially, GET and POST logic should proceed at least partly along a common path. The design idea of HttpServlet however was to offer doGet(), doPost() etc implementations answering a 'not supported' error depending on HTTP version. These stubs would be useful to inherit if you needed to return such an answer.<br/> In summary, the API/ interface is complete -- but the functionality is definitively not. Thus it is declared as abstract.
The javax.servlet.Servlet interface defines the life cycle methods of servlet such as init(), service() and destroy(). The Web container invokes the init(), service() and destroy() methods of a servlet during its life cycle.
<strong>1.</strong> GET <strong>2.</strong> POST <strong>3.</strong> PUT <strong>4.</strong> DELETE <strong>5.</strong> OPTIONS <strong>6.</strong> HEAD <strong>7.</strong> TRACE
A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods <strong>GET, PUT, DELETE, HEAD, and OPTIONS are idempotent </strong>method and we should implement our application to make sure these methods always return same result. HTTP method <strong>POST is non-idempotent</strong> method and we should use post method when implementing something that changes with every request.
The <strong>Content-Type</strong> response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.
Web Applications are modules that requires to run on server to handle the request and return the response. Java provides web application support through Servlets and JSPs that can run in a servlet container and provide dynamic content to client browser.<br/> Java Web Applications are packaged as Web Archive (WAR) and it has following folders in it.<br/> <strong>WEB-INF :</strong> contains the lib directory(application dependencies), classes(contains java servlet files) and web.xml(Deployment Descriptor)<br/> <strong>META-INF: </strong> contains MANIFEST.MF<br/> <STRONG>webapp:</strong> contains all the static pages like .html , .js etc
It is a method in which the output of one servlet is piped into the next servlet.<br/> It is the last servlet in the chain that provides the output to the Web browser.
javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object by calling servlet's init() method.A servlet is initialized only once in its life cycle and hence the init() method is called only once per servlet by a web server.
This will be the first statement if we are overriding the init(config) method by this way we will store the config object for future reference and we can use by getServletConfig() to get information about config object if will not do this config object will be lost and we have only one way to get config object because servlet pass config object only in init method . Without doing this if we call the ServletConfig method will get NullPointerException.
javax.servlet.ServletContext interface provides access to web application parameters to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using <context-param> element.
ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.<br/> ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used to provide application level init parameters that all other servlets can use.<br/> We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.
Yes we can call like this but if we have not overridden this method container will call the default method and nothing will happen.after calling this if any we have overridden the method then the code written inside is executed.
<strong>include()</strong> Includes the response of another servlet into the calling servlet. This method can be invoked from calling servlet while servicing the request. It includes contents of resource such as Servlet, JSP page or HTML page in response.<br/> <strong>forward() </strong> mehod is used to forward requests to resource such as Servlet, JSP file or HTML page on the server. I implies that after invoking forward() method, the servlet can not add any response content.
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.<br/> There are two methods defined in this interface:<br/> <strong>void forward(ServletRequest request, ServletResponse response)</strong> – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.<br/> <strong>void include(ServletRequest request, ServletResponse response) </strong>– includes the content of a resource (servlet, JSP page, HTML file) in the response.
<strong>1.</strong>PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. <br/> <strong>2.</strong>We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.<br/> <strong>3.</strong>We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.
Http is a stateless, client-side pull only protocol.To implement a stateful conversation over it, Java EE Web Server need to hide some information (which is sessionid) in client-side and the mechanism it can use should follow HTTP and HTML spec.<br/> There are three ways to accomplish this goal:<br/> <strong>Cookies </strong> - Server will ask browser to maintain a cookie.<br/> <strong>Hidden Form Field </strong> - server will add an additional parameter at every form in HTML<br/> <strong>URL Rewriting </strong> - Server will add an additional parameter at the end of URL link
Using cookies is the simplest and easiest way to track a session.A unique session id (stored in the form of a cookie) is sent by the server to the client as a part of the response and the same session id saved with the client is sent to the server as a part of the request which helps the server to recognize the unique client session.
<strong>encodeURL() </strong>is used for all URLs in a servlet's output. It helps session ids to be encoded with the URL.<br/> <strong>encodeRedirectURL() </strong> is used with res.sendRedirect only. It is also used for encoding session ids with URL but only while redirecting.
Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:<br/> To intercept requests from a client before they access a resource at back end.<br/> To manipulate responses from server before they are sent back to the client.
We can configure them in web.xml like below:<br/> <error-page><br/> <error-code>400</error-code><br/> <location>/BadRequestExceptionHandler</location ><br/> </error-page ><br/><br/> <error-page><br/> <exception-type >javax.servlet.ServletException</exception-type><br/> <location>/BadRequestExceptionHandler</location><br/> </error-page>
Usually servlet container loads a servlet on the first client request but sometimes when the servlet is heavy and takes time to loads, we might want to load it on application startup. We can use load-on-startup element with servlet configuration in web.xml file or use WebServlet annotation loadOnStartup variable to tell container to load the servlet on system startup.<br/> <br/> <servlet><br/> <servlet-name>bar</servlet-name><br/> <servlet-class>com.bar.servlets.Bar</servlet-class><br/> <load-on-startup>1</load-on-startup><br/> </servlet> <br/><br/> The load-on-startup value should be int, if it’s negative integer then servlet container will load the servlet based on client requests and requirement but if it’s 0 or positive, then container will load it on application startup.<br/> If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will be loaded first.
one simple way to call doPost() method inside doGet() and doGet()method inside doPost() it will create deadlock situation for a servlet.
Servlet creates only one instance either request is 100 or 200.
Wrappers are sandwiched between servlet classes and servlet environments by wrapping servlet APIs. Wrappers allow to add additional functionalities to the request and response object given by the servlet container.<br/> Filters can also use wrappers to wrap request or response.Servlet 3.0 provide following 4 wrapper classes.<br/> <strong>1.</strong> java.serlet.ServletRequestWrapper<br/> <strong>2.</strong> javax.servlet.ServletResponseWrapper<br/> <strong>3.</strong> javax.servlet.http.HTTPServletResponseWrapper
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.