June 07, 2011

Servlets interview-questions-3

51) Can I send multiple responses for a single request?

No. That doesn't even make sense :-)
You can, however, send a "redirect", which tells the user's browser to send another request, possibly to the same servlet with different parameters. Search this FAQ on "redirect" to learn more.

52) What is FORM based login and how do I use it? Also, what servlet containers support it?

Form based login is one of the four known web based login mechanisms. For completeness I list all of them with a description of their nature:
  1. HTTP Basic Authentication
    • An authentication protocol defined within the HTTP protocol (and based on headers). It indicates the HTTP realm for which access is being negotiated and sends passwords with base64 encoding, therefore it is not very secure. (See RFC2068 for more information.)
  2. HTTP Digest Authentication
    • Like HTTP Basic Authentication, but with the password transmitted in an encrypted form. It is more secure than Basic, but less then HTTPS Authentication which uses private keys. Yet it is not currently in widespread use.
  3. HTTPS Authentication (SSL Mutual Authentication)
    • This security mechanism provides end user authentication using HTTPS (HTTP over SSL). It performs mutual (client & server) certificate based authentication with a set of different cipher suites.
  4. Form Based Login
    • A standard HTML form (static, Servlet/JSP or script generated) for logging in. It can be associated with protection or user domains, and is used to authenticate previously unauthenticated users.
    • The major advantage is that the look and feel of the login screen can be controlled (in comparison to the HTTP browsers' built in mechanisms).
To support 1., 3., and 4. of these authentication mechanisms is a requirement of the J2EE Specification (as of v1.2, 3.4.1.3 Required Login Mechanisms). (HTTP Digest Authentication is not a requirement, but containers are encouraged to support it.)
You can also see section 3.3.11.1 of the J2EE Specs. (User Authentication, Web Client) for more detailed descriptions of the mechanisms.
Thus any Servlet container that conforms to the J2EE Platform specification should support form based login.
To be more specific, the Servlet 2.2 Specification describes/specifies the same mechanisms in 11.5 including form based login in 11.5.3.
This section (11.5.3) describes in depth the nature, the requirements and the naming conventions of form based login and I suggest to take a look at it.
Here is a sample of a conforming HTML login form:


 
    
    
 
Known Servlet containers that support FORM-based login are:
  • iPlanet Application Server
  • Tomcat (the reference implementation of the Java Servlet API)

53) How do I capture a request and dispatch the exact request (with all the parameters received) to another URL?

As far as i know it depends on the location of the next target url.
  • If the next servlet url is in the same host, then you can use the forward method.
Here is an example code about using forward:


 RequestDispatcher rd = null;
 String targetURL = "target_servlet_name";
 ServletContext ctx = this.getServletContext();
 rd = ctx.getRequestDispatcher(targetURL);
 rd.forward(request, response);

54) How can the data within an HTML form be refreshed automatically whenever there is a change in the database?

JSP is intended for dynamically generating pages. The generated pages can include wml, html, dhtml or whatever you want...
When you have a generated page, JSP has already made its work. From this moment you have a page.
If you want automatic refreshing, then this should be acomplished by the technology included in the generated page (JSP will tell only what to include in the page).
The browser can not be loaded by extern factors. The browser is the one who fetches url's since the http protocol is request-response based. If a server can reload a browser without its allow, it implies that we could be receiving pages which we haven't asked for from servers.
May you could use applets and a ServerSocket for receiving incoming signals from the server for changed data in the DB. This way you can load new information inside the applet or try to force a page reload.
[That's a nice idea -- it could use the showDocument() call to reload the current page. It could also use HTTP polling instead of maintaining an expensive socket connection. -Alex]
Perhaps (if possible), could be simpler using an automatic JavaScript refreshing function that force page reload after a specified time interval.

55) What is a web application (or "webapp")?

A web application is a collection of servlets, html pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors. A web application is rooted at a specific path within a web server. For example, a catalog application could be located at http://www.mycorp.com/catalog. All requests that start with this prefix will be routed to the ServletContext which represents the catalog application.

56) How can I call a servlet from a JSP page? How can I pass variables from the JSP that the servlet can access?

You can use or response.sendRedirect("http://path/YourServlet").
Variables can be sent as:


       
 
 
  

You may also pass parameters to your servlet by specifying response.sendRedirect("http://path/YourServlet?param1=val1").

57) Can there be more than one instance of a servlet at one time ?

It is important to note that there can be more than one instance of a given Servlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to use.

58) How can I measure the file downloading time using servlets?



 ServletOutputStream out = response.getOutputStream();
 String filename = getServletContext().getRealPath(request.getQueryString());
 FileInputStream fin = new FileInputStream(filename);
 long start = System.currentTimeMillis();
 byte data[] = new byte[1024];
 int len = 0;
 while ((len = fin.read(data)) > 0) {
    out.write(data, 0, len);
 }
 out.flush();
 long stop = System.currentTimeMills();
 log("took " + (stop - start) + "ms to download " + filename);
 

59) What is inter-servlet communication?

As the name says it, it is communication between servlets. Servlets talking to each other. [There are many ways to communicate between servlets, including
  • Request Dispatching
  • HTTP Redirect
  • Servlet Chaining
  • HTTP request (using sockets or the URLConnection class)
  • Shared session, request, or application objects (beans)
  • Direct method invocation (deprecated)
  • Shared static or instance variables (deprecated)
Search the FAQ, especially topic Message Passing (including Request Dispatching) for information on each of these techniques. -Alex]
Basically interServlet communication is acheived through servlet chaining. Which is a process in which you pass the output of one servlet as the input to other. These servlets should be running in the same server.
e.g. ServletContext.getRequestDispatcher(HttpRequest, HttpResponse).forward("NextServlet") ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet.
There are some Servlet engine specific configurations for servlet chaining.
Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a handle to the desired servlet through the ServletContext Object by passing it the servlet name ( this object can return any servlets running in the server). And then calling the function on the returned Servlet object.
e.g. TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet"); otherServletDetails= Test.getServletDetails();
You must be careful when you call another servlet's methods. If the servlet that you want to call implements the SingleThreadModel interface, your call could conflict with the servlet's single threaded nature. (The server cannot intervene and make sure your call happens when the servlet is not interacting with another client.) In this case, your servlet should make an HTTP request to the other servlet instead of direct calls.
Servlets could also invoke other servlets programmatically by sending an HTTP request. This could be done by opening a URL connection to the desired Servlet.

60) How do I make servlet aliasing work with Apache+Tomcat?

When you use Tomcat standalone as your web server, you can modify the web.xml in $TOMCAT_HOME/webapps/myApp/WEB-INF to add a url-pattern:


 


    
      
   myServlet
      
      
   myServlet
      
    
    
      
   myServlet
      
      
       /jsp-bin/*
      
   
 

This will let you use: http://webserver:8080/myApp/jsp-bin/stuff.html instead of: http://webserver:8080/myApp/servlet/myServlet/stuff.html But it won't work on port 80 if you've integrated Tomcat with Apache. Graeme Wallace provided this trick to remedy the situation. Add the following to your tomcat-apache.conf (or to a static version of it, since tomcat re-generates the conf file every time it starts):


 
   LocationMatch /myApp/jsp-bin/* 
   SetHandler jserv-servlet


 LocationMatch

This lets Apache turn over handling of the url pattern to your servlet.

61) Is there any way to determine the number of concurrent connections my servlet engine can handle?

Depends on whether or not your servlet container uses thread pooling. If you do not use a thread pool, the number of concurrent connections accepted by Tomcat 3.1, for example, is 10. This you can see for yourself by testing a servlet with the Apache JMeter tool.
However, if your servlet container uses a thread pool, you can specify the number of concurrent connections to be accepted by the container. For Tomcat 3.1, the information on how to do so is supplied with the documentation in the TOMCAT_HOME/doc/uguide directory.

62) What is a request dispatcher and how does it work?

A RequestDispatcher object can forward a client's request to a resource or include the resource itself in the response back to the client. A resource can be another servlet, or an HTML file, or a JSP file, etc.
You can also think of a RequestDispatcher object as a wrapper for the resource located at a given path that is supplied as an argument to the getRequestDispatcher method.
For constructing a RequestDispatcher object, you can use either the ServletRequest.getRequestDispatcher() method or the ServletContext.getRequestDispatcher() method. They both do the same thing, but impose slightly different constraints on the argument path. For the former, it looks for the resource in the same webapp to which the invoking servlet belongs and the pathname specified can be relative to invoking servlet. For the latter, the pathname must begin with '/' and is interpreted relative to the root of the webapp.
To illustrate, suppose you want Servlet_A to invoke Servlet_B. If they are both in the same directory, you could accomplish this by incorporating the following code fragment in either the service method or the doGet method of Servlet_A:

 
 RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B");
 dispatcher.forward( request, response );

where request, of type HttpServletRequest, is the first parameter of the enclosing service method (or the doGet method) and response, of type HttpServletResponse, the second. You could accomplish the same by

 
 RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/servlet/Servlet_B" );
 dispatcher.forward( request, response );

63) What is a Servlet Context?

A Servlet Context is a grouping under which related servlets (and JSPs and other web resources) run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.
The ServletContext object is used by an individual servlet to "call back" and obtain services from the container (such as a request dispatcher). Read the JavaDoc for javax.servlet.ServletContext for more information.
You can maintain "application global" variables by using Servlet Context Attributes.

64) Does the RequestDispatcher expect a relative URL to be relative to the originally-called servlet or to the current servlet (if different)?

Since the RequestDispatcher will be passing the control (request object and response object) from the current Servlet, the relative URL must be relative to the current servlet.
The originally called servlet has passed the control to the current servlet, and now current servlet is acting as controller to other resourses.

65) What is the difference between in-process and out-of-process servlet containers?

The in-process Servlet containers are the containers which work inside the JVM of Web server, these provides good performance but poor in scalibility.
The out-of-process containers are the containers which work in the JVM outside the web server. poor in performance but better in scalibility
In the case of out-of-process containers, web server and container talks with each other by using the some standard mechanism like IPC.
In addition to these types of containers, there is 3rd type which is stand-alone servlet containers. These are an integral part of the web server.

66) How is SingleThreadModel implemented in Tomcat? In other containers? [I would assume that Tomcat uses its connection thread pool, and creates a new instance of the servlet for each connection thread, instead of sharing one instance among all threads. Is that true?]

The question mixes together two rather independent aspects of a servlet container: "concurrency control" and "thread pooling".
Concurrency control, such as achieved by having a servlet implement the SingleThreadModel interface, addresses the issue of thread safety. A servlet will be thread-safe or thread-unsafe regardless of whether the servlet container used a thread pool. Thread pooling merely eliminates the overhead associated with the creation and destruction of threads as a servlet container tries to respond to multiple requests received simultaneously. It is for this reason that the specification document for Servlet 2.2 API is silent on the subject of thread pooling -- as it is merely an implementation detail. However, the document does indeed address the issue of thread safety and how and when to use SingleThreadModel servlets.
Section 3.3.3.1 of the Servlet 2.2 API Specification document says that if a servlet implements the SingleThreadModel it is guaranteed "that only one request thread at time will be allowed in the service method." It says further that "a servlet container may satisfy this guarantee by serializing requests on a servlet or by maintaining a pool of servlet instances."
Obviously, for superior performance you'd want the servlet container to create multiple instances of a SingleThreadModel type servlet should there be many requests received in quick succession. Whether or not a servlet container does that depends completely on the implementation. My experiments show that Tomcat 3.1 does indeed create multiple instances of a SingleThreadModel servlet, but only for the first batch of requests received concurrently. For subsequent batches of concurrent requests, it seems to use only one of those instances.

67) Which servlet containers have persistent session support? Specifically, does Tomcat 3.1?

All servlet containers that implement the Servlet 2.2 API must provide for session tracking through either the use of cookies or through URL rewriting. All Tomcat servlet containers support session tracking.

68) Can I use JAAS as the authentication technology for servlets ?

Yes, JAAS can be used as authentication technology for servlets. One important feature of JAAS is pure Java implementation. The JAAS infrastructure is divided into two main components: an authentication component and an authorization component. The JAAS authentication component provides the ability to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet.

69) How can I set a servlet to load on startup of the container, rather than on the first request?

The Servlet 2.2 spec defines a load-on-startup element for just this purpose. Put it in the section of your web.xml deployment descriptor. It is either empty () or contains "a positive integer indicating the order in which the servlet should be loaded. Lower integers are loaded before higher integers. If no value is specified, or if the value specified is not a positive integer, the container is free to load it at any time in the startup sequence."
For example,


       
    foo
    com.foo.servlets.Foo
    5
 

Some servlet containers also have their own techniques for configuring this; please submit feedback with information on these.

70) Is it possible to write a servlet that acts as a FTP server?

Yes. It would spawn a thread that opens a ServerSocket, then listens for incoming connections and speaks the FTP protocol.

71) Is there a way to disable a user's ability to double-click a submit image/button (and therefore submitting duplicate data -- multiple submits)? Is there a way to do this with Javascript?

Give the submit image (or button) an onClick() handler. Have the handler check if a flag is set and if not set the flag and submit the form and then clear the form.

72) What are the main differences between Servlets and ISAPI?

The first difference is obviously that Servlets is the technology from Sun Microsystems and ISAPI is from Microsoft.
Other Differences are:
  1. Servlet is a simple .class file and ISAPI is a DLL
  2. Servlets run in the Servlet containers and may be in-process or out of process. ISAs run in the same address space as the HTTP server
  3. Servlet container preprocesses and postprocesses the data communication between the client and server. ISAPI Filters provide the capability of pre-processing and post-processing of all data sent between the client and the server
  4. Java is the only choice for writing Servlets, VC++/MFC is used to write ISAPI code
  5. Servlets works on most of the Web servers plus third party containers can be integrated with other web servers to provide servlets on them. ISAPI works on only ISAPI-compliant Web server (for example, Microsoft Internet Information Server)
  6. Servlets can connect to the Databases through JDBC as well as jdbc-odbc bridges. ISAPI can connect to Databases through only ODBC
  7. Servlets have access to many server-side technologies like EJB and etc. ISAPI is limited in scope
  8. Multiple commands can be implemented in a servlet by using pathinfo. ISAPI allows multiple commands in one DLL, implemented as member functions of the CHttpServer object in the DLL.
  9. Content generation and content presentation can be done seperately in Servlets with the help of JSP. ISAPI code has to generate HTML code itself.

73) Can I associate a servlet with a particular mime-type, so if the client requests a file of that type, my servlet will be executed?

In web.xml you can use a mime-mapping to map the type with a certain extension and then map the servlet to that extension.


    
      zzz
    
    
      text/plain
    
 

 
    
      *.zzz
     
    
      MyServlet
    
 

So, when a file for type zzz is requested, the servlet gets called.

74) What are the different cases for using sendRedirect() vs. getRequestDispatcher()?

When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher.
If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.
If you don't need to preserve the request/response objects, you can use either.

75) How do I access the value of a cookie using JavaScript?

You can manipulate cookies in JavaScript with the document.cookie property. You can set a cookie by assigning this property, and retrieve one by reading its current value.
The following statement, for example, sets a new cookie with a minimum number of attributes:


 document.cookie = "cookieName=cookieValue";

And the following statement displays the property's value:


 alert(document.cookie);

The value of document.cookie is a string containing a list of all cookies that are associated
with a web page. It consists, that is, of name=value pairs for each cookie that matches the
current domain, path, and date. The value of the document.cookie property, for instance,
might be the following string:


 cookieName1=cookieValue1; cookieName2=cookieValue2;

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts