Servlets experienced interview question/Servlets Interview Questions and Answers for Freshers & Experienced

How many important interfaces do we have in filter concept?

a. Filter: It is useful for developing web applications.
b. FilterConfig: It is useful for reading the data from web.xml file under <init-param> tags. Every Filter object having their own Filter-Config object
c. FilterChain: It is useful for making communication between Filter to Servlet.

Who will call Filter life cycle methods?

All the Filter life cycle methods are calling by ServletContainer. That’s why we are calling filter is one servlet container managed object.

How to store, delete and read the data in scope objects?

To insert the data into scope objects, we have setAttribute(-,-) and to read the data from scope objects, we have getAttributed(-) and to delete the data from scope objects we have removeAttribute().

How many types of cookies do we have in Servlet?

We have two types of cookies.
a. Persistence cookie.
b. Non-persistence cookie.
Non-Persistence cookie:
The cookie is available up to before closing browser is called Non-persistence cookies.
Persistence cookie:
The cookies are available after closing the browser also available up to end user sign out or logout is called persistence cookie.
This is simple technique and existed at client side. The drawback of cookie is we can send only textual information. Once browser side, if we are disable the cookie we unable maintain session tracking.

What is use of sendRedirect process in servlet?

If we want make a communication between one servlet project to another servlet project within the two different servers we should go for sendRedirect process.

What are the drawbacks of GenericServlet?

When ever client sending the request data, that data will be attached to browser URL and visible to everyone so security problem.
We cannot get http protocol specification like
? Security:
? Request Header information.
? Session tracking
?No redirecting process.
To overcome the above problems we should go for HttpServlet interface.

What is session ID?

A session ID is an unique identification string usually a long, random and alpha numeric string, that is transmitted between the client and the server.

Session IDs are usually stored in the cookies, URLs ( in case url rewriting) and hidden fields of Web pages.

What are the two important API’s in for Servlets?

Two important packages are required to build servlet “javax.servlet” and javax.servlet.http.

They form the core of Servlet API. Servlets are not part of core Java but are standard extension provided by Tomcat.

Can we explicitly destroy a servlet object?

No, we cannot destroy a servlet explicitly it’s all done by the container.

Even if you try calling the destroy method container does not respond to it.

How are Servlets developed?

Developing Servlets is a three step process

Write the Servlet:
1. import javax.servlet.*;
2. public class extends GenericServlet
3. over-ride service() method and give the business logic, if any
4. print the message/results to the client.

Install the Servlet:
1. The source file generated as above should be compiled with JDK 1.1 or later version and the resulting .class file (say MyServlet.class) should be put (copied) in the directory, C :JavaServer 1.0 servlets

2. Start and run the local host, i.e. C: JavaServer1.0inhttpd, which runs on port no. 8080

Run the Servlet:
Start the browser. Type the following as the URL address. http://localhost:8080/servlet/MyServlet

What is Servlet Runner?

1. The Servlet Runner is a small utility, intended for testing. It is multi-threaded, and it can run more than one Servlet. It can be used, therefore, to run multiple Servlets simultaneously, or to test one Servlet that calls other Servlets in order to satisfy client request.
2. Unlike some web servers, it does not automatically reload Servlets when they are updated.
3. It assumes that servletrunner is running on the machine, localhost, at port 8080, and that they MyServlet program is located in the Servlet directory provided to Servlet Runner to startup.

What are the advantages of Servlets over CGI?

Servlets offer several advantages over CGI

1. Better performance – Servlets execute within the address space of a web server.
2. Separate process – They create a separate process to handle each client request.
3. Platform independent – Servlets are platform – independent, because they are written in Java.
4. Security – More secure.
5. Functionality – The full functionality of the Java class libraries is available to a Servlet. It can communicate with applets, databases, or other software using sockets or RMI mechanisms.

What is Server Side Include?

Server Side Include (SSI) is just another way to load and invoke local as well as remote Servelts.

What is meant by Pre-initialization of Servlet?

When servlet container is loaded, all the servlets defined in the web.xml file are not initialized by default. But the container receives the request it loads the servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of servlet. In case of Pre-initialization, the servlet is loaded.

Differentiate between Servlet and Applet?

Servlet are server side components that execute on the server whereas applets are client side components and execute on the web browser. Applets have GUI interface but there is not GUI interface in case of Servlets.

Why HTTP protocol called as a stateless protocol?

A protocol is stateless if it cannot remember difference between one client request and the other. HTTP is a stateless protocol because each request is executed independently without any knowledge of the requests that came before it.

What is the difference between ServletContext and PageContext?

ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request.

What are the type of protocols supported by HTTPServlet?

It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HTTPServlet only supports HTTP and HTTPS protocol.

What mechanisms are used by a Servlet Container to maintain Session Information?

Servlet Container uses Cookies, URL rewriting and HTTPS protocol information to maintain the session.

What are different Authentication options available in servlets?

There are four ways of authentication
1. HTTP basic authentication: In HTTP basic authentication the server uses the username and password send by the client. The password is sent using simple base64 encoding but it's not encrypted.
2. HTTP digest authentication: HTTP digest authentication is same as HTTP basic authentication but the biggest difference is password is encrypted and transmitted using SHA or MD5.
3. HTTPS client authentication: HTTPS client authentication is based on HTTP over SSL. It requires that the end client should posses a PKC (Public Key Certificate). This verifies the browsers identity.
4. Form based authentication: In Form based the web container invokes a login page. The invoked login page is used to collect username and password.

What are the two important API's in for Servlets?

1. Two important packages are required to build servlet "javax.servlet" and javax.servlet.http.
2. They form the core of Servlet API. Servlets are not part of core Java but are standard extension provided by Tomcat.

What is use of RequetDispatcher object?

This is useful for making a communication between one servlet to another servlet, jsp, html, txt.

How many Servlet Execution Model do we have servlet?

A) There are two execution models in servlet.
a. Single Instance Single Thread Model
b. Single Instance Multi Thread Model.

Explain the architecture of the Servlet Life Cycle?

The different components in the architecture of the Servlet Life Cycle are Servlet, Servlet Container, Web Server, a network established between the servlet container and the client web browser. The different methods of a servlet instance can be called once the servlet is enabled to initialize by the servlet container. Servlet is a thread-safe component. A Servlet Container instantiates different servlets in the form of different threads where each servlet’s lifecycle can be handled in each thread. Many servlet threads can be instantiated and they will be managed by the Servlet Container efficiently. The Servlet Container complies with the Java EE Standards in a Server.

What are the new features added to Servlet 3?

1) Servlet Annotations
2) Web Fragments
3) Web components addition dynamically
4) Asynchronous Processing

What is <session-timeout> ?

The element <session-timeout> is used for specifying the timeout of a Session. This is how it is defined in the web.xml file.
<session-config>
<session-timeout>35</session-timeout>
</session-config>
It would set the session timeout to 25 minutes.

Explain Servlet chaining?

Servlet chaining is a concept where the request is processed in a chain of servlets. First Servlet processes the request partially and passes to the second one, then second servlet process it and passes to third one and so on. The last servlet returns the response to the client (browser).

What are the different types of session tracking mechanism supported by Servlets?

1) URL rewriting
2) Hidden Form Fields
3) Cookies
4) Secure Socket Layer(SSL) Sessions

What is the use of <load-on-startup>?

<load-on-startup> is used for specifying the Servlet files which needs to be loaded during server startup. The servlet files specified in this element are loaded as soon as the server starts, it does not wait for the first request for loading them up. This is how it is specified in web.xml file.

<servlet>
<servlet-name>MyServletNameHere</servlet-name>
<servlet-class>ServletClassHere-FullyQualified</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
If more than one files are specified then the files will be loaded in the same order in which they have been specified in it.

doGet() Vs doPost() methods?

1) In doGet(), the parameters are visible in the address bar, they get appended to the URL. In doPost() parameters are not visible in the address bar.
2) You can maximum transfer 1024 characters through GET request. doPost() doesn’t have any limitations.
3) doGet() is not good for sensitive data as the parameters do not get encrypted. In doPost() the parameters are encrypted hence it is more secure compared to doGet().
4) Method doGet() allow you to bookmark the resource. doPost() doesn’t allow bookmarks.
5) doGet() is faster compared to the doPost() method.

Static webpage vs Dynamic webpage?

The webpages which are same for all the users are static webpages and the webpages that are dynamically generated based on the user’s request (that may be different for each user depending on the request) are known as dynamic webpages. Servlet is mainly used for dynamic webpages.

What is JSESSIONID in Java? When does JSESSIONID gets created?

One of my favorite Servlet JSP Interview questions for 2 to 4 years of experience programmers on web development. The JSESSIONID is a cookie which is used to manage session in Java web application. JSESSIONID is created by Web Container whenever a new session is created. You can further see a course like JSP, Servlets, and JDBC for Beginners: Build a Database App to learn more about how JSP and Servlet application works together.

How do you create a cookie using servlet?

Creating and Setting cookies using servlet involves the following steps:

Step 1: Creating a Cookie object
Call the Cookie constructor with a cookie name and a cookie value, both of String Datatype. Care should be taken that these particular symbols( [ ] ( ) = , ” / ? @ : ;) are excluded while declaring name and values.
Cookie cookie = new Cookie("key","value");
Step 2: Setting the maximum age
We shall use setMaxAge to specify how long the cookie should be valid. Following code-segment would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);

Step 3: Sending the Cookie into the HTTP response headers

We can use response.addCookie to add cookies in the HTTP response header as follows:

response.addCookie(cookie);

How do you configure a centralized error handler in servlets?

If we wish to include a central Error Handler for all the exceptions then we can define following error-page instead of defining separate error-page elements for an individual exception

<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>

Explain JSESSIONID and when is it created?

JSESSIONID is basically a cookie that is used to manage the session in a Java Web Application. It is created by the Web Container when a new session is created.

Why do we use sendredirect() method?

The sendredirect() method basically works at the client-side. It is used to redirect the response to another resource like Servlet, JSP, HTML.
The syntax for sendredirect() method is as follows:
void send Redirect(URL);

Example:

response.sendredirect(“http://www.google.com”);

Explain Web Container.

A web container or a Servlet container is used to interact with the Servlet and includes all the Servlet, JSP, XML files inside it. Web Container’s responsibility is to manage the life cycle of a servlet and to help to map the URL of a specific servlet. A web container is also used creates the object of a servlet.

How do you get the IP address of the client in servlet?

We can use the following code to get the client IP address in servlet.

request.getRemoteAddr()

Write a simple Servlet program to print the contents of HTML.

We can print the contents of HTML using the following steps:
Step 1: Get the object of PrintWriter using request.
PrintWriter out = response.getWriter();
Step 2: Now print HTML.
out.println("Hello World");

What is the ServletConfig object?

javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has its own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation.

What do you mean by MIME type?

The “Content-Type” response header is called MIME (Multipurpose Internet Mail Extensions) Type. The server sends MIME type to the client to let the client know the kind of data it’s sending. It helps the client in rendering the data for the user. Some of the most commonly used mime types are text/HTML, text/XML, application/XML.

Can we fetch the attributes related to a servlet on a different servlet?

The attributes of another servlet that we are looking for can be accessed by using its name. The syntax is described as follows:
1. Context.setAttribute (“name”,” value”)
2. Context.getAttribute (“name”)

Why do we need to implement a Single Thread model in the case of Servlet.

In J2EE we can implement our servlet in two different ways either by using:
1. Single Thread Model
2. Multithread Model
Depending upon our scenario, if we have implemented single thread means only one instance is going handle one request at a time no two thread will concurrently execute service method of the servlet.
Example
In banking accounts where sensitive data is handled mostly this scenario was used this interface is deprecated in Servlet API version 2.4. As the name signifies multi-thread means a servlet is capable of handling multiple requests at the same time. This servlet interview question was quite popular a few years back on entry-level but now it's losing its shine.

How can 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”)

Can we call destroy() method inside the init() method is yes what will happen?

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. You can further see these Servlet and JSP courses to learn more.

What is the workflow of a servlet?

Servlet is a Java tool that is used to create Java Web Applications. It is located at the server-side and helps to generate dynamic web pages, it acts as a mediator between the incoming HTTP request from the browser and the database. Servlet is robust and called as a server-side programming language.

Explain MVC pattern.

Model-View-Controller (MVC) is a design pattern that divides a software application into three segments namely the Model, the View and the Controller.

1. A model deals with the behaviour of the application. It contains the data and business logic of the application. It notifies views and controllers when there is a change in its state.
2. A view renders the information to the user so that it looks attractive and appealing. It takes information from the model using which it generates output.
3. A controller takes input from a user and sends the command to model or view. It controls the flow of the application.

Can a JSP be called using a Servlet?

Yes, Servlet can call a JSP using RequestDispatcher interface.
Example:
1. RequestDispatcher reqdis=request.getRequestDispatcher("log.jsp");
2. reqdis.forward(request,response);

What is the use of RequestDispatcher Interface?

The RequestDispatcher interface defines the object that receives the request from the client and dispatches it to the resources such as a servlet, JSP, HTML file. The RequestDispatcher interface has the following two methods:
public void forward(ServletRequest request, ServletResponse response)
Forwards request from one servlet to another resource like servlet, JSP, HTML etc.

public void include(ServletRequest request, ServletResponse response)
Includes the content of the resource such as a servlet, JSP, and HTML in the response.

What are the annotations used in Servlet 3?

The important 3 annotations used in the servlets are.

1. @WebServlet : for servlet class.
2. @WebListener : for listener class.
3. @WebFilter : for filter class.

Search
R4R Team
R4R provides Servlets Freshers questions and answers (Servlets Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,Servlets experienced interview question,Servlets Freshers & Experienced Interview Questions and Answers,Servlets Objetive choice questions and answers,Servlets Multiple choice questions and answers,Servlets objective, Servlets questions , Servlets answers,Servlets MCQs questions and answers Java, C ,C++, ASP, ASP.net C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for Servlets fresher interview questions ,Servlets Experienced interview questions,Servlets fresher interview questions and answers ,Servlets Experienced interview questions and answers,tricky Servlets queries for interview pdf,complex Servlets for practice with answers,Servlets for practice with answers You can search job and get offer latters by studing r4r.in .learn in easy ways .