Tuesday, 26 June 2012

servlets interview questions

Servlets Faqs-->5


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;


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:

        <input type="button" onClick="window.print(0)" value="Print This Page">

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:

        <servlet>
           <servlet-name>myservlet</servlet-name>
           <servlet-class>com.mypackage.MyServlet</servlet-class>
        </servlet>
        <servlet-mapping>
           <servlet-name>myservlet</servlet-name>
           <url-pattern>/myservlet</url-pattern>
        </servlet-mapping>

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:

        <servlet-mapping>
           <servlet-name>
             jsp
           </servlet-name>
           <url>*.html</url>
        </servlet-mapping>
And comment out the following block

        <mime-mapping>
           <extension>
             html
           </extension>
           <mime-type>
             text/html
           </mime-type>
        </mime-mapping>

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:

        <FORM ACTION="/foo/myservlet">
           <INPUT TYPE="HIDDEN" NAME="redirect" VALUE="/foo/thisjsp.jsp">
              Shoe size: <INPUT NAME="shoesize">
           <INPUT TYPE="SUBMIT">
        </FORM>
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).



0 comments:

Post a Comment