Servlet Interview Questions
What are the life cycle methods of a servlet?
Servlet Life Cycle consists of three methods:
public void init(ServletConfig config)
Used container to initialize the servlet, this method is invoked only once in the lifecycle of servlet.
public void service(ServletRequest request, ServletResponse response)
Called once for every request, the container can’t invoke the service() method till the init() method is executed.
public void destroys()
Invoked once when the servlet is unloaded from memory.
What is the difference between GET and POST method?
- GET is a safe method (idempotent) where POST is a non-idempotent method.
- We can send limited data with the GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.
- GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar requests again, POST is secure because data is sent in the request body and we can’t bookmark it.
- GET is the default HTTP method whereas we need to specify method as POST to send the request with the POST method. Hyperlinks in a page uses GET method.
What is ServletContext in Servlet JSP
ServletContext is even more important than ServletConfig and its one per web application, also known as Context. This object is common for all the servlet and they use this object to communicate with the servlet container to get the detail of the whole web application or execution environment important thing to remember is, it represents a web application in single JVM.
Signature: public interface ServletContextServlet Config
- Servlet config object represent single servlet
- Its like local parameter associated with a particular servlet
- It’s a name-value pair defined inside the servlet section of web.xml file so it has servlet wide scope
- getServletConfig() method is used to get the config object
- In Shopping cart of a user is a specific to particular user so here we can use servlet config
Servlet Context
- It represents whole web application running on particular JVM and common for all the servlet
- Its like global parameter associated with the whole application
- ServletContext has application-wide scope so define outside of servlet tag in web.xml file.
- getServletContext() method is used to get the context object.
- To get the MIME type of a file or application session related information is stored using the servlet context object.
What are the advantages of Servlet over CGI?
Servlet technology was developed to overcomes problems with CGI.
- Servlets are robust because container takes care of the life cycle of servlet and we don’t need to worry about memory leaks, security, garbage collection, etc.
- Servlets provide better performance than CGI in terms of processing time, memory utilization because servlets use benefits of multithreading and for each request, a new thread is created, which is faster than creating new Objects per request in CGI.
- Servlets are platform and system independent, The web App with Servlet can run on a standard web container such as Tomcat, Jetty, JBoss, Glassfish servers and on operating systems such as Windows, Linux, etc.
What is servlet collaboration?
Communication between two servlets is called servlet collaboration.
It can b done in 3 ways
1). RequestDispatchers include () and forward() method .
2). Using sendRedirect()method of Response object.
3). Using servlet Context methods
How you get the information about one servlet context in another servlet?
In context object, we can set the attribute which we want on another servlet and we can get that attribute using their name on another servlet. Context.setAttribute ("name"," value") Context.getAttribute ("name")Servlet is an important part of any J2EE development and serves as Controller on many web MVC frameworks and that’s why it’s quite popular on J2EE interviews
Difference between the web server and the application server?
- A web server's responsibility is to handler HTTP requests from client browsers and responds with 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 the servlet container, for example, Tomcat.
- Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as the servlet container, for example, Tomcat.
What are the different ways for servlet authentication?
The Servlet Container provides different ways of login based servlet authentication.
Following are the types
- HTTP Basic Authentication
- HTTP Digest Authentication
- HTTPS Authentication
- Form-Based Login: A standard HTML form for authentication, the advantage is that we can change the login page layout as our application requirements rather than using HTTP built-in login mechanisms.
How to get the IP address of the client in servlet?
We can use request.getRemoteAddr() to get the client IP address in servlet.
How to get the server information in a servlet?
We can use the below code snippet to get the servlet information in a servlet through a servlet context
obj. getServletContext().getServerInfo()
What is use URL Rewriting?
We use HttpSession for session management in servlets but it works with Cookies and we can disable the cookie in the client browser.
Servlet API provides support for URL rewriting that we can use to manage session in this case.
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 are redirecting the request to another resource and we want to provide session information,
we can use encodeRedirectURL() method.
What is a deployment descriptor?
The deployment descriptor is a configuration file for the web application and its name is web.xml and present in WEB-INF directory.
Servlet container web.xml to configure web application servlets, servlet config params, context init params, filters, listeners, welcome, and error handlers pages.
In servlet 3.0 annotations, we can remove a lot of clutter from web.xml by configuring servlets, filters, and listeners using annotations.
In ServletContext, we can create an attribute with application scope that all other servlets can access but we can initialize ServletContext init parameters as String only in the deployment descriptor (web.xml). What if our application is database-oriented and we want to set an attribute in ServletContext for Database Connection.
If the application has a single entry point (user login), then you can do it in the first servlet request but if we have multiple entry points then doing it everywhere will result in a lot of code redundancy.
Also if the database is not configured properly, we won’t know until the first client request comes to the server. To overcome this, servlet API provides Listener interfaces that we can implement and configure to listen to an event and do certain operations.
How we inform that session when the session is invalidated or timed-out?
If we have to make sure an object gets notified when the session is destroyed, the object should implement javax.servlet.http.HttpSessionBindingListener interface. This interface defines two callback methods – valueBound() and valueUnbound() that we can define to implement processing logic when the object is added as an attribute to the session and when the session is destroyed. Recommended reading Servlet Listener.
What are the servlet filters?
Servlet Filters are pluggable components used to intercept and process requests before they are sent to servlets and response after servlet code is finished and before the container sends the response back to the client.
The task we can do in filters :
- Logging request parameters to log files.
- Authentication and Authorization of request for resources.
- Formatting of request body and header before sending it to the servlet.
- Compression of the response data sent to the client.
- Change response by adding some cookies, header information, etc.
Difference between encodeRedirectUrl and encodeURL?
HttpServletResponse provides a method to encode URL in HTML hyperlinks so that the special characters and white spaces are escaped and append the session id to the URL.
It behaves similarly to URLEncoder encode method with an additional process to append the Jsessionid parameter at the end of the URL.
HttpServletResponse encodeRedirectUrl() method is used specially for encode the redirect URL in response.
While doing URL rewriting support, for hyperlinks in HTML response, we have to use encodeURL() method whereas for the redirect URL we should use encodeRedirectUrl() method.
What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?
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 the client with status code 302 (redirect) with URL to send the request, which is a completely new request.
sendRedirect() method that required an extra network call.
forward() is handled internally by the container whereas sendRedirect() is handled by the browser.
We have to use forward() when accessing resources in the same application
In forward() browser is unaware of the actual processing resource and the URL in the address bar remains the same
In the sendRedirect() URL in address bar change to the forwarded resource.
forward() can’t be used to invoke a servlet in another context, we can only use sendRedirect() in this case.
Why we have to override the service() method?
When the servlet container receives a client request, it invokes the service() method which in turn invokes the doGet(), doPost() methods based on the HTTP method of request.
The whole purpose of the service() method is to forward to request corresponding HTTP method implementations.
If we have to do some pre-processing of requests, we can always use servlet filters and listeners.
We can use PrintWriter and ServletOutputStream both in a servlet?
We can’t get instances of both PrintWriter and ServletOutputStream in a single servlet method if we invoke both the methods; getWriter() and getOutputStream() on response;
We will get java.lang.IllegalStateException at runtime with the message as another method has already been called for this response.
What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP, or another servlet in the same application.
We can also use this to include the content of another resource to the response. This is used for inter-servlet communication in the same context.
There are two methods defined in this interface:
- void forward(ServletRequest request, ServletResponse response): It forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
- void include(ServletRequest request, ServletResponse response): This is used to 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. It must begin with / and is interpreted as relative to the current context root.
Different tasks performed by Servlet Container?
Servlet containers are also known as web container, for example, Tomcat. Some of the important tasks of servlet container are:- Communication Support: Servlet Container provides an easy way of communication between web clients (Browsers) and the servlets and JSPs. Because of the container, we don’t need to build a server socket to listen for any request from the web client, parse the request, and generate a response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications.
- Lifecycle and Resource Management: It is responsible for managing the life cycle of a servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. The container also provides utility like JNDI for resource pooling and management.
- Multithreading Support: It creates a new thread for every request to the servlet and provides them request and response objects to the processing. So servlets are not initialized for each request and save time and memory. JSP Support: JSPs don’t look like normal java classes but every JSP in the application is compiled by container and converted to Servlet and then container manages them like other servlets.
- Miscellaneous Task: It manages the resource pool, performs memory optimizations, executes garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.
In this article, we have seen Servlet Interview Questions and Answers
0 Comments
Post a Comment