Dear Readers, Welcome to Servlets Interview Questions and Answers have been designed specially to get you acquainted with the nature of questions you may encounter during your Job interview for the subject of Servlets. These Servlets Questions are very important for campus placement test and job interviews. As per my experience good interviewers hardly plan to ask any particular questions during your Job interview and these model questions are asked in the online technical test and interview of many IT companies.
A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request\/response paradigm.
Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.
The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.
/bookstore/education/index.html
context path: /bookstore
servlet path: /education
path info: /index.html
A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.
I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.
The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()
1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)
You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.
You can use a client-side Refresh or Server Push
Using System.exit(1); in try block will not allow finally code to execute.
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.
The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial).
Servlet interface.
Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.
An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.
Container writes a no argument constructor for our servlet.
Container creates instance of servlet by calling Class.forName(className).newInstance().
Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.
We can give relative URL when we use ServletRequest and not while using ServletContext.
Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.
CGI programs run outside the webserver. So a new process must be started to execute a CGI program. CGI programs are designed to handle a single request at a time. After that they return the result to the web server and exit.
On the other hand servlets can handle multiple requests concurrently. They run within web servers. They generate dynamic content that is easier to write and faster to run.
Servlets are the programs that run under web server environment. A copy of Servlet class can handle numerous request threads. In servlets, JVM stays running and handles each request using a light weight thread.
Servlets life cycle involve three important methods, i.e. init, service and destroy.
Init()
Init method is called when Servlet first loaded in to the web server memory.
Service()
Once initialized, Servlets stays in memory to process requests. Servlets read the data provided in the request in the service() method.
Destroy()
When server unloads servlets, destroy() method is called to clean up resources the servlet is consuming.
There are four ways of Authentication options available in servlets
HTTP basic authentication
In this, server uses the username and password provided by the client and these credentials are transmitted using simple base64 encoding.
HTTP digest authentication
This option is same the basic authentication except the password is encrypted and transmitted using SHA or MD5.
HTTPS client authentication
This options is based on HTTP over SSL.
Form-based authentication
Form-based authentication uses login page to collect username and password.
GenericServlet makes writing servlets easier. To write a generic servlet, all you need to do is to override the abstract service method.
Applets:
• Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers.
• An Applet is a client side java program that runs within a Web browser on the client machine.
• An applet can use the user interface classes like AWT or Swing.
• Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy()
Servlets:
• Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server.
• Servlet is a server side component which runs on the web server.
• The servlet does not have a user interface.
• Servlet Methods: doGet(), doPost()
Both are interfaces in the package javax.servlet:
• ServletConfig is a servlet configuration object. It is used by a servlet container to pass information to a servlet during initialization.
• The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.
• The ServletContext object is contained within the ServletConfig object. It is provided by the web server to the servlet when the servlet is initialized.
• ServletContext is an interface which has a set of methods like getServletName(), getServletContext(), getInitParameter(), getInitParameterNames(). The servlet uses to interact with its servlet container.
• ServletContext is common to all servlets within the same web application. So, servlets use ServletContext to share context information.
getSession(true) will check whether a session already exists for the user. If yes, it will return that session object else it will create a new session object and return it.
getSession(false) will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.
Servlets are Java based analog to CGI programs, implemented by means of a servlet container associated with an HTTP server. Servlets run on the server side. Beans are reusable code components written in Java that one can use in a variety of programming environments. JavaBeans are to Java what ActiveX controls are to Microsoft. Javabeans can run on server side, client side, within an applet etc.
So, both have nothing in common except Java.
Servlet mapping controls how you access a servlet. It is recommended that you don’t use absolute URLs. Instead usage of relative URLs should be done.
If you try to deploy the application with a different context root, you might have to change all the urls used in all the JSP programs. Relative URLs is the solution so that you can deploy your application with different context root with out changing the URLs.
Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream.
Servlets are used to extend the server side functionality of a website. They communicate with various application on the server side and respond to the request made by the client.
A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.
ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.
ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.