June 07, 2011

Servlets interview-questions-4

76) How do I write to a log file using JSP under Tomcat? Can I make use of the log() method for this?

Yes, you can use the Servlet API's log method in Tomcat from within JSPs or servlets. These messages are stored in the server's log directory in a file called servlet.log.

77) How can I use a servlet to print a file on a printer attached to the client?

The security in a browser is designed to restrict you from automating things like this. However, you can use JavaScript in the HTML your servlet returns to print a frame. The browser will still confirm the print job with the user, so you can't completely automate this. Also, you'll be printing whatever the browser is displaying (it will not reliably print plug-ins or applets), so normally you are restricted to HTML and images.
[The JavaScript source code for doing this is:


 

78) How do you do servlet aliasing with Apache and Tomcat?

Servlet aliasing is a two part process with Apache and Tomcat. First, you must map the request in Apache to Tomcat with the ApJServMount directive, e.g.,
ApJServMount/myservlet/ROOT
Second, you must map that url pattern to a servlet name and then to a servlet class in your web.xml configuration file. Here is a sample exerpt:


 
    myservlet
    com.mypackage.MyServlet
 
 
    myservlet
    /myservlet
 

79) I want my servlet page to redirect to a login page if the session has timed out. How can I know if my session has timed out?

If the servlet engine does the time-out, following code should help you:


 //assume you have a HttpServletRequest request
 if(request.getSession(false)==null) {
    //no valid session (timeouted=invalid)

    //code to redirect to login page
 }

80) Can Tomcat be configured to interpret all, or selected, .html files within a given context as JSP? Or, do JSP files have to end with a .jsp extension?

yes you can do that by modifying the web.xml file. You will have to invoke the org.apache.jasper.runtime.JspServlet for all the requests having extension .html. You can do that by changing the Servlet mapping code:


 
    
      jsp
    
    *.html
 

And comment out the following block


 
    
      html
    
    
      text/html
    
 

81) What is the difference between request attributes, session attributes, and ServletContext attributes?

A ServletContext attribute is an object bound into a context through ServletContext.setAttribute() method and which is available to ALL servlets (thus JSP) in that context, or to other contexts via the getContext() method. By definition a context attribute exists locally in the VM where they were defined. So, they're unavailable on distributed applications.
Session attributes are bound to a session, as a mean to provide state to a set of related HTTP requests. Session attributes are available ONLY to those servlets which join the session. They're also unavailable to different JVMs in distributed scenarios. Objects can be notified when they're bound/unbound to the session implementing the HttpSessionBindingListener interface.
Request attributes are bound to a specific request object, and they last as far as the request is resolved or while it keep dispatched from servlet to servlet. They're used more as comunication channel between Servlets via the RequestDispatcher Interface (since you can't add Parameters...) and by the container. Request attributes are very useful in web apps when you must provide setup information between information providers and the information presentation layer (a JSP) that is bound to a specific request and need not be available any longer, which usually happens with sessions without a rigorous control strategy.
Thus we can say that context attributes are meant for infra-structure such as shared connection pools, session attributes to contextual information such as user identification, and request attributes are meant to specific request info such as query results.

82) Are singleton/static objects shared between servlet contexts?

[Question continues: For example if I have two contexts on a single web server, and each context uses a login servlet and the login servlet connects to a DB. The DB connection is managed by a singleton object. Do both contexts have their own instance of the DB singleton or does one instance get shared between the two?]
It depends on from where the class is loaded.
The classes loaded from context's WEB-INF directory are not shared by other contexts, whereas classes loaded from CLASSPATH are shared. So if you have exactly the same DBConnection class in WEB-INF/classes directory of two different contexts, each context gets its own copy of the singleton (static) object.

83) When building web applications, what are some areas where synchronization problems arrise?

In general, you will run into synchronization issues when you try to access any shared resource. By shared resource, I mean anything which might be used by more than one request.
Typical examples include:
  • Connections to external servers, especially if you have any sort of pooling.
  • Anything which you include in a HttpSession. (Your user could open many browser windows and make many simultaneous requests within the one session.)
  • Log destinations, if you do your own logging from your servlets.

84) What is the difference between apache webserver, java webserver and tomcat server?

Apache is an HTTP server written in C that can be compiled and run on many platforms.
Java WebServer is an HTTP server from Sun written in Java that also supports Servlets and JSP.
Tomcat is an open-source HTTP server from the Apache Foundation, written in Java, that supports Servlets and JSP. It can also be used as a "plug-in" to native-code HTTP servers, such as Apache Web Server and IIS, to provide support for Servlets (while still serving normal HTTP requests from the primary, native-code web server).

85) How can you embed a JavaScript within servlets / JSP pages?

You don't have to do anything special to include JavaScript in servlets or JSP pages. Just have the servlet/JSP page generate the necessary JavaScript code, just like you would include it in a raw HTML page.
The key thing to remember is it won't run in the server. It will run back on the client when the browser loads the generate HTML, with the included JavaScript.

86) How can I make a POST request through response.sendRedirect() or response.setStatus() and response.setHeader() methods?

You can't. It's a fundamental limitation of the HTTP protocol. You'll have to figure out some other way to pass the data, such as
  • Use GET instead
  • Make the POST from your servlet, not from the client
  • Store data in cookies instead of passing it via GET/POST

87) How do I pass a request object of one servlet as a request object to another servlet?

Use a Request Dispatcher.

88) I call a servlet as the action in a form, from a jsp. How can I redirect the response from the servlet, back to the JSP? (RequestDispatcher.forward will not help in this case, as I do not know which resource has made the request. request.getRequestURI will return the uri as contained in the action tag of the form, which is not what is needed.)

You'll have to pass the JSP's URI in to the servlet, and have the servlet call sendRedirect to go back to the JSP. For example:


 
Shoe size:

Then in the servlet...


 response.sendRedirect(request.getParameter("redirect"));

89) What is the ServletConfig object, and why is it useful?

The ServletConfig object is an interface. It contains the methods
  • getInitParameter
  • getInitParameterNames
  • getServletContext
  • getServletName
You can use the methods to determine the Servlet's initialization parameters, the name of the servlets instance, and a reference to the Servlet Context the servlet is running in.
getServletContext is the most valuable method, as it allows you to share information accross an application (context).

90) I have a global variable in a servlet class. What will happen to this global variable if two requests hit on the same time?

What will happen is an unforeseeable event.
The best way to establish a default occurrence (the servlet handles a request at a time) is to synchronize the access to the global variable or alternatively to create a servlet that implements the SingleThreadModel interface.

91) Suppose I have 2 servers, server1 and server2. How can I take data in a cookie from server1, and send it to server2?

You'll have to create a (new) similar cookie on server 2.
Have a ReadCookieServlet running on server1 that
  • Reads the cookie, using request.getCookies()
  • Redirects to WriteCookieServlet running on server2, passing the cookie name, value and expiration date as request parameters, using response.sendRedirect().
Have a WriteCookieServlet running on server2 that
  • Reads the cookie name, value and expiration date request parameters, using request.getParameter().
  • Creates a similar cookie, using response.addCookie().

92) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context?

There are three ways I can think of off the top of my head:
  1. Store the information you want to share in a persistant format, such as in a file system or database. That way, any servlet that is running in a JVM that can "see" these resources can get to this information.
  2. If persisting this information is not an option, you can bind this information to a context that is accessible to all servlet contexts, such as the application server's context. This way, you can keep the data you want to share in memory.
  3. Use the old fashion way of passing information to a servlet - HTTP. One servlet could foward a request to another servlet and include the data that needs to be shared as parameters in the request.

93) How can I write an "error page" -- that is, a servlet or JSP to report errors of other servlets?

The Servlet 2.2 specification allows you to specify an error page (a servlet or a JSP) for different kinds of HTTP errors or ServletExceptions. You can specify this in deployment descriptor of the web application as:


 
    FooException
    /error.jsp
  

where FooException is a subclass of ServletException.
The web container invokes this servlet in case of errors, and you can access the following information from the request object of error servlet/JSP: error code, exception type, and a message.

94) What is the difference between ServletContext and ServletConfig?

A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object.
This notion of a web application became very significant upon the Servlet 2.1 API, where you could deploy an entire web application in a WAR file. Notice that I always said "servlet instance", not servlet. That is because the same servlet can be used in several web applications at one time. In fact, this may be common if there is a generic controller servlet that can be configured at run time for a specific application. Then, you would have several instances of the same servlet running, each possibly having different configurations.
This is where the ServletConfig comes in. This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.

95) Under what circumstances will a servlet be reloaded?

That depends on the Servlet container.
Most of the Servlet containers reload the servlet only it detects the code change in the Servlet, not in the referenced classes.
In Tomcat's server.xml deployment descriptor, if you have mentioned


 Context path="/myApp" 
   docBase="D:/myApp/webDev" 
   crossContext="true"
   debug="0"
   reloadable="true"
   trusted="false" 
 Context

The reloadable = true makes the magic. Every time the Servlet container detects that the Servlet code is changed, it will call the destroy on the currently loaded Servlet and reload the new code.
But if the class that is referenced by the Servlet changes, then the Servlet will not get loaded. You will have to change the timestamp of the servlet or stop-start the server to have the new class in the container memory.

96) What is a Servlet Filter?

A filter is basically a component that is invoked whenever a resource is invoked for which the filter is mapped. The resource can be something like a servlet, or a URL pattern. A filter normally works on the request, response, or header attributes, and does not itself send a response to the client.

97) I am using the RequestDispatcher's forward() method to redirect to a JSP. The problem is that the jsp's url is now relative to the servlet's url and all my url's in the jsp such as will be corrupt. How do I solve this problem?

You can use absolute urls like:

       BODY
    String base = request.getContextPath(); 
    IMG src="%=base%>/img/pic.gif"
 BODY
or write out a BASE tag like:

 String base = request.getContextPath(); 
 HEAD
    BASE HREF="<%=base%>"
 HEAD
 BODY
    
 


That should take care of the problem.

98) How can I return a readily available (static) HTML page to the user instead of generating it in the servlet?

To solve your problem, you can either send a "Redirect" back to the client or use a RequestDispatcher and forward your request to another page:
  1. Redirect:
  2. A redirection is made using the HttpServletResponse object:
    
     if(condition) {
        response.sendRedirect("page1.html");
     } else {
               response.sendRedirect("page2.html");
     }
    
  3. RequestDispatcher:
  4. A request dispatcher can be obtained through the ServletContext. It can be used to include another page or to forward to it.
    
     if(condition) {
        this.getServletContext()
      .getRequestDispatcher("page1.html").forward();
     } else {
       this.getServletContext()
      .getRequestDispatcher("page2.html").forward();
     }
    
Both solutions require, that the pages are available in you document root. If they are located somewhere else on your filesystem, you have to open the file manually and copy their content to the output writer.
If your application server is set up in combination with a normal web server like Apache, you should use solution (1), because the the web server usually serves static files much faster than the application server.

99) What is the difference between static variables and instance variables in a servlet?

According to the Java Language definition, a static variable is shared among all instances of a class, where a non-static variable -- also called an instance variable -- is specific to a single instance of that class.
According to the Servlet specification, a servlet that does not declare SingleThreadModel usually has one and only one instance, shared among all concurrent requests hitting that servlet.
That means that, in servlets (and other multithreaded applications), an instance variable behaves very much like a static variable, since it is shared among all threads. You have to be very careful about synchronizing access to shared data.
The big difference between instance variables and static variables comes when you have configured your servlet engine to instantiate two instances of the same servlet class, but with different init parameters. In this case, there will be two instances of the same servlet class, which means two sets of instance variables, but only one set of static variables.
Remember that you can store data in lots of different places in a servlet. To wit:
  • Local variables - for loop iterators, result sets, and so forth
  • Request attributes - for data that must be passed to other servlets invoked with the RequestDispatcher
  • Session attributes - persists for all future requests from the current user only
  • Instance variables - for data that persists for the life of the servlet, shared with all concurrent users
  • Static variables - for data that persists for the life of the application, shared with all concurrent users -- including any other servlet instances that were instantiated with different init parameters
  • Context attributes - for data that must persist for the life of the application, and be shared with all other servlets

100) How can I share data between two different web applications?

Different servlets may share data within one application via ServletContext. If you have a compelling to put the servlets in different applications, you may wanna consider using EJBs.

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