What is different between web server and application server?
A web server is responsible to handle HTTP requests from client browsers and respond to HTML response. A web server understands HTTP language and runs on HTTP protocol.
Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat.
Application Servers provides additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management, etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications.
What is a servlet?
Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
All servlets must implement the Java. Servlet. Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as
doGet()and doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using the HTTP protocol and that’s why we mostly extend HttpServlet class.
What are the uses of Servlet?
Typical uses for HTTP Servlets include:
- Processing and/or storing data submitted by an HTML form.
- Providing dynamic content, e.g. returning the results of a database query to the client.
- A Servlet can handle multiple request concurrently and be used to develop high performance systems.
- Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.
What is the life cycle of Servlet?
Following is the life cycle of Servlet:
Why do we need a constructor in a servlet if we use the init method?
Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet’s constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven’t constructed an object to call it on yet.
How the servlet is loaded?
A servlet can be loaded when:
- First request is made.
- Server starts up (auto-load).
- There is only a single instance, which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
- Administrator manually loads.
How a Servlet is unloaded?
A servlet is unloaded when:
- Server shuts down.
- Administrator manually unloads.
What is deployment descriptor?
web.xmlfile of a web application is known as deployment descriptor. It is usually placed in the WEB-INF folder of application.
It has the information like Servlet name, Servlet mapping, etc. This file tells the Servlet container which Servlet class needs to be called for the given URL pattern.
What is Servlet interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or more commonly by extending a class that implements it.
Are Servlets Thread Safe?
HttpServlet init() method and destroy() method are called only once in a servlet life cycle, so we don’t need to worry about their synchronization. But service methods such as doGet() or doPost() are getting called in every client request and since the servlet uses multi threading, we should provide thread safety in these methods.
How to achieve thread safety in servlets?
If there are any local variables in service methods, we don’t need to worry about their thread safety because they are specific to each thread, but if we have a shared resource then we can use synchronization to achieve thread safety in servlets when working with shared resources.
What is SingleThreadModel interface?
SingleThreadModel interface was provided for thread safety and it guarantees that no two threads will execute concurrently in the servlet’s service method. However SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. Also it takes out all the benefits of multi threading support of servlets, that’s why this interface is Deprecated in Servlet 2.4.
Explain the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle the requests. HttpServlet extends GenericServlet and adds support for
doGet(), doPost(), doPut(), doOptions(), doDelete(), doTrace()methods.
GenericServlet does not support any protocol. HTTPSeervlet support HTTP and HTTPS protocol.
GenericServlet cannot handle cookies and session while HTTPServlet can handle them.
What is ServletConfig?
javax.servlet.ServletConfigis used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object.
We can provide servlet init parameters in
web.xmlfile or through use of WebInitParam annotation. We can use getServletConfig()method to get the ServletConfig object of the servlet.
What is ServletContext?
javax.servlet.ServletContextinterface 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.xmlusing <context-param> element.
We can get the ServletContext object via the
getServletContext()method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.
ServletContext is enhanced in Servlet Specs 3 to introduce methods through which we can programmatically add Listeners and Filters and Servlet to the application. It also provides some utility methods such as
Explain the difference between ServletConfig and ServletContext?
ServletConfigas the name implies provide the information about the configuration of a servlet which is defined inside the web.xmlfile or we can say deployment descriptor. Its a specific object for each servlet. ServletContextis an application specific object which is shared by all the servlet belongs to one application in one JVM. This is a single object which represents our application and all the servlet access application specific data using this object. Servlet also use their method to communicate with the container.
What is RequestDispatcher?
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.
There are two methods defined in this interface:
- void forward(ServletRequest request, ServletResponse response): forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
- void include(ServletRequest request, ServletResponse response): includes the content of a resource (servlet, JSP page, HTML file) in the response.
We can get RequestDispatcher in a servlet using ServletContext
getRequestDispatcher(String path)method. The path must begin with a / and is interpreted as relative to the current context root.
How do we call one servlet from another servlet?
We can use RequestDispatcher
forward()method to forward the processing of a request to another servlet.
If we want to include the another servlet output to the response, we can use RequestDispatcher
How can we invoke another servlet in a different application?
We cannot use RequestDispatcher to invoke servlet from another application because it’s specific for the application. If we have to forward the request to a resource in another application, we can use ServletResponse
sendRedirect()method and provide complete URL of another servlet.
What is session management?
Session management is a mechanism for maintaining state across multiple HTTP requests. This is managed by the web container. In other words it is a technique to hold some values passed by user across multiple HTTP requests arising out from a single browser instance.
What are different methods of session management in servlets?
- User Authentication
- HTML Hidden Field
- URL Rewriting
- Session Management API
What is a HTML Hidden Field?
Hidden Fields are nothing but normal HTML form element with type Hidden to store the user data across HTTP request.
How to manage session using Cookies?
Cookies are used a lot in web client-server communication, it’s not something specific to java. Cookies are text data sent by server to the client and it gets saved at the client local machine.
Servlet API provides cookies support through
javax.servlet.http.Cookieclass that implements Serializable and Cloneable interfaces.
getCookies()method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
addCookie(Cookie c)method is provided to attach cookie in response header, there are no getter methods for cookie.
What is URL Rewriting?
We can use HttpSession for session management in servlets but it works with Cookies and we can disable the cookie in client browser. Servlet API provides support for URL rewriting that we can use to manage session in this case.
The best part is that from coding point of view, it’s very easy to use and involves one step – encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if browser cookies are disabled.
We can encode URL with HttpServletResponse
encodeURL()method and if we have to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL()method.
What is HTTP Session in servlets?
Session tracking in Servlets is done by using Interface HttpSession. It helps to identify a client throughout many page requests or visiting a website and to store details about that client.
HttpSession session = request.getSession();
- If user already has a session the existing session is returned.
- If no session exists a new one is created and returned.
- If you want to know if this is a new session: call the Session
How to invalidate a session in servlet?
How to notify an object in session when session is invalidated or timed-out?
If we have to make sure an object gets notified when session is destroyed, the object should implement
This interface defines two callback methods –
valueBound()and valueUnbound()that we can define to implement processing logic when the object is added as attribute to the session and when session is destroyed.
What is servlet chaining?
Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.
What are the Scope Objects available?
Enables sharing information among collaborating web components via attributes maintained in Scope objects.Attributes are name/object pairs.Attributes maintained in the Scope objects are accessed with
Scope objects are four types:
- Web Context: Accessible from Web components within a Web context
- Session: Accessible from Web components handling a request that belongs to the session
- Request: Accessible from Web components handling the request
- Page: Accessible from JSP page that creates the object
What is servlet filters?
Servlet Filters are pluggable java components that we can use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.
Some common tasks that we can do with filters are:
- Logging request parameters to log files.
- Authentication and autherization of request for resources.
- Formatting of request body or header before sending it to servlet.
- Compressing the response data sent to the client.
- Alter response by adding some cookies, header information etc.