June 07, 2011

Servlets interview-questions-1

1) Is it the "servlets" directory or the "servlet" directory?

For Java Web Server:
  • on the file system, it's "servlets"
  • c:\JavaWebServer1.1\servlets\DateServlet.class
  • in a URL path, it's "servlet"
  • http://www.stinky.com/servlet/DateServlet

2) How do I support both GET and POST protocol from the same Servlet?

The easy way is, just support POST, then have your doGet method call your doPost method:


 public void doGet(HttpServletRequest req, HttpServletResponse res)
 throws ServletException, IOException
 {
    doPost(req, res); 
 }

3) How do I ensure that my servlet is thread-safe?

This is actually a very complex issue. A few guidelines:
  1. The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don't have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method.
  2. Every new client request generates (or allocates) a new thread; that thread calls the service() method of your servlet (which may in turn call doPost(), doGet() and so forth).
  3. Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other's toes. This means that you should be careful to synchronize access to shared data (instance variables) using the synchronized keyword.
  4. (Note that the server will also allocate a new instance if you register the servlet with a new name and, e.g., new init parameters.)
  5. Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn't synchronize the service() method! (Or doPost(), doGet() et al.)
  6. A simple solution to synchronizing is to always synchronize on the servlet instance itself using "synchronized (this) { ... }". However, this can lead to performance bottlenecks; you're usually better off synchronizing on the data objects themselves.
  7. If you absolutely can't deal with synchronizing, you can declare that your servlet "implements SingleThreadModel". This empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: "If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe." Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it's more difficult to share data across instances than within a single instance.
  8. See also What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
  9. To share data across successive or concurrent requests, you can use either instance variables or class-static variables, or use Session Tracking.
  10. The destroy() method is not necessarily as clean as the init() method. The server calls destroy either after all service calls have been completed, or after a certain number of seconds have passed, whichever comes first. This means that other threads might be running service requests at the same time as your destroy() method is called! So be sure to synchronize, and/or wait for the other requests to quit. Sun's Servlet Tutorial has an example of how to do this with reference counting.
  11. destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the "closing a JDBC connection" example in Sun's Tutorial.

4) What is the difference between URL encoding, URL rewriting, HTML escaping, and entity encoding?

URL Encoding is a process of transforming user input to a CGI form so it is fit for travel across the network -- basically, stripping spaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to JDK 1.2, aka Java 2).
Example: changing "We're #1!" into "We%27re+%231%21"
URL Rewriting is a technique for saving state information on the user's browser between page hits. It's sort of like cookies, only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of the Servlet API, sometimes uses URL Rewriting when cookies are unavailable.
Example: changing into

5) How do I upload a file to my servlet or JSP?

On the client side, the client's browser must support form-based upload. Most modern browsers do, but there's no guarantee. For example,


 

The input type "file" brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.
When the user clicks the "Upload" button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867.
Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.
Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet.
Please note that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that.

6) How does a servlet communicate with a JSP page?

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.


 public void doPost (HttpServletRequest request,
   HttpServletResponse response) {
 
     try {
      govi.FormBean f = new govi.FormBean();
      String id = request.getParameter("id");
      f.setName(request.getParameter("name"));
      f.setAddr(request.getParameter("addr"));
      f.setAge(request.getParameter("age"));
       //use the id to compute 
       //additional bean properties like info 
  //maybe perform a db query, etc.
       // . . .
       f.setPersonalizationInfo(info);
      request.setAttribute("fBean",f);
      getServletConfig().getServletContext().getRequestDispatcher
        ("/jsp/Bean1.jsp").forward(request, response);
    } catch (Exception ex) {
      . . .
    }
  }

The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.


 
 
 
 
 

7) What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?

Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

8) Can a servlet maintain a JTA UserTransaction object across multiple servlet invocations?

No. A JTA transaction must start and finish within a single invocation (of the service() method). Note that this question does not address servlets that maintain and manipulate JDBC connections, including a connection's transaction handling.

9) How does the performance of JSP pages compare with that of servlets? How does it compare with Perl scripts?

The performance of JSP pages is very close to that of servlets. However, users may experience a perceptible delay when a JSP page is accessed for the very first time. This is because the JSP page undergoes a "translation phase" wherein it is converted into a servlet by the JSP engine. Once this servlet is dynamically compiled and loaded into memory, it follows the servlet life cycle for request processing. Here, the jspInit() method is automatically invoked by the JSP engine upon loading the servlet, followed by the _jspService() method, which is responsible for request processing and replying to the client. Do note that the lifetime of this servlet is non-deterministic - it may be removed from memory at any time by the JSP engine for resource-related reasons. When this happens, the JSP engine automatically invokes the jspDestroy() method allowing the servlet to free any previously allocated resources.
Subsequent client requests to the JSP page do not result in a repeat of the translation phase as long as the servlet is cached in memory, and are directly handled by the servlet's service() method in a concurrent fashion (i.e. the service() method handles each client request within a seperate thread concurrently.)
There have been some recent studies contrasting the performance of servlets with Perl scripts running in a "real-life" environment. The results are favorable to servlets, especially when they are running in a clustered environment.

10) How do I call one servlet from another servlet?

[ Short answer: there are several ways to do this, including
  • use a RequestDispatcher
  • use a URLConnection or HTTPClient
  • send a redirect
  • call getServletContext().getServlet(name) (deprecated, doesn't work in 2.1+)
- Alex ]
It depends on what you mean by "call" and what it is you seek to do and why you seek to do it.
If the end result needed is to invoke the methods then the simplest mechanism would be to treat the servlet like any java object , create an instance and call the mehods.
If the idea is to call the service method from the service method of another servlet, AKA forwarding the request, you could use the RequestDispatcher object.
If, however, you want to gain access to the instance of the servlet that has been loaded into memory by the servlet engine, you have to know the alias of the servlet. (How it is defined depends on the engine.) For example, to invoke a servlet in JSDK a servlet can be named by the property


 myname.code=com.sameer.servlets.MyServlet

The code below shows how this named servlet can be accessed in the service method of another servlet


 public void service (HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
    ...
    MyServlet ms=(MyServlet) getServletConfig().getServletContext().getServlet("myname");
    ...
 }

That said, This whole apporach of accessing servlets in another servlets has been deprecated in the 2.1 version of the servlet API due to the security issues. The cleaner and better apporach is to just avoid accessing other servlets directly and use the RequestDispatcher instead.

11) What are all the different kinds of servers? (Such as Web Servers, Application Servers, etc)

The servers involved in handling and processing a user's request break down into a few basic types, each of which may have one or more tasks it solves. This flexibility gives developers a great deal of power over how applications will be created and deployed, but also leads to confusion over what server is able to, or should, perform a specific task.
Starting at the basic level, a user is typically submitting a request to a system through a web browser. (We are conveniently ignoring all other types of clients (RMI, CORBA, COM/DCOM, Custom, etc..) for the time being for purposes of clarity.) The web request must be received by a Web Server (otherwise known as an HTTP Server) of some sort. This web server must handle standard HTTP requests and responses, typically returning HTML to the calling user. Code that executes within the server environment may be CGI driven, Servlets, ASP, or some other server-side programming language, but the end result is that the web server will pass back HTML to the user.
The web server may need to execute an application in response to the users request. It may be generating a list of news items, or handling a form submission to a guest book. If the server application is written as a Java Servlet, it will need a place to execute, and this place is typically called a Servlet Engine. Depending on the web server, this engine may be internal, external, or a completely different product. This engine is continually running, unlike a traditional CGI environment where a CGI script is started upon each request to the server. This persistance gives a servlet connection and thread pooling, as well as an easy way to maintain state between each HTTP request. JSP pages are usually tied in with the servlet engine, and would execute within the same space/application as the servlets.
There are many products that handle the web serving and the servlet engine in different manners. Netscape/iPlanet Enterprise Server builds the servlet engine directly into the web server and runs within the same process space. Apache requires that a servlet engine run in an external process, and will communicate to the engine via TCP/IP sockets. Other servers, such as MS IIS don't officially support servlets, and require add-on products to add that capability.
When you move on to Enterprise JavaBeans (and other J2EE components like JMS and CORBA) you move into the application server space. An Application Server is any server that supplies additional functionality related to enterprise computing -- for instance, load balancing, database access classes, transaction processing, messaging, and so on.
EJB Application Servers provide an EJB container, which is the environment that beans will execute in, and this container will manage transactions, thread pools, and other issues as necessary. These application servers are usually stand-alone products, and developers would tie their servlets/JSP pages to the EJB components via remote object access APIs. Depending on the application server, programmers may use CORBA or RMI to talk to their beans, but the baseline standard is to use JNDI to locate and create EJB references as necessary.
Now, one thing that confuses the issue is that many application server providers include some or all of these components in their product. If you look at WebLogic (http://www.beasys.com/) you will find that WebLogic contains a web server, servlet engine, JSP processor, JMS facility, as well as an EJB container. Theoretically a product like this could be used to handle all aspects of site development. In practice, you would most likely use this type of product to manage/serve EJB instances, while dedicated web servers handle the specific HTTP requests.

12) Should I override the service() method?

No. It provides a fair bit of housekeeping that you'd just have to do yourself. If you need to do something regardless of whether the request is e.g., a POST or a GET, create a helper method and call that at the beginning of e.g., doPost() and doGet().

13) How can my application get to know when a HttpSession is removed (when it time-outs)?

Define a class, say SessionTimeoutNotifier, that implements javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutNotifier object and add it to the user session. When the session is removed, SessionTimeoutNotifier.valueUnbound() will be called by the servlet engine. You can implement valueUnbound() to do whatever you want.

14) Why use JSP when we can do the same thing with servlets?

[Original question: Why should I use JSP when there is already servlet technology available for serving dynamic content?]
While JSP may be great for serving up dynamic Web content and separating content from presentation, some may still wonder why servlets should be cast aside for JSP. The utility of servlets is not in question. They are excellent for server-side processing, and, with their significant installed base, are here to stay. In fact, architecturally speaking, you can view JSP as a high-level abstraction of servlets that is implemented as an extension of the Servlet 2.1 API. Still, you shouldn't use servlets indiscriminately; they may not be appropriate for everyone. For instance, while page designers can easily write a JSP page using conventional HTML or XML tools, servlets are more suited for back-end developers because they are often written using an IDE -- a process that generally requires a higher level of programming expertise.
When deploying servlets, even developers have to be careful and ensure that there is no tight coupling between presentation and content. You can usually do this by adding a third-party HTML wrapper package like htmlKona to the mix. But even this approach, though providing some flexibility with simple screen changes, still does not shield you from a change in the presentation format itself. For example, if your presentation changed from HTML to DHTML, you would still need to ensure that wrapper packages were compliant with the new format. In a worst-case scenario, if a wrapper package is not available, you may end up hardcoding the presentation within the dynamic content. So, what is the solution? One approach would be to use both JSP and servlet technologies for building application systems.

15) How do I send information and data back and forth between applet and servlet using the HTTP protocol?

Use the standard java.net.URL class, or "roll your own" using java.net.Socket. See the HTTP spec at W3C for more detail.
Note: The servlet cannot initiate this connection! If the servlet needs to asynchronously send a message to the applet, then you must open up a persistent socket using java.net.Socket (on the applet side), and java.net.ServerSocket and Threads (on the server side).

16) Can I get the path of the current servlet where it lives on the file system (not its URL)?

Try using:


 request.getRealPath(request.getServletPath())

An example may be:


  out.println(request.getRealPath(request.getServletPath()));

17) How can I daisy chain servlets together such that the output of one servlet serves as the input to the next?

There are two common methods for chaining the output of one servlet to another servlet :
  1. the first method is the aliasing which describes a series of servlets to be executed
  2. the second one is to define a new MIME-Type and associate a servlet as handlers As I don't really use the second one, I'll focus on the aliasing.
To chain servlets together, you have to specify a sequential list of servlets and associate it to an alias. When a request is made to this alias, the first servlet in the list is invoked, processed its task and sent the ouptut to the next servlet in the list as the request object. The output can be sent again to another servlets.
To accomplish this method, you need to configure your servlet engine (JRun, JavaWeb server, JServ ...).
For example to configure JRun for servlet chaining, you select the JSE service (JRun servlet engine) to access to the JSE Service Config panel. You have just to define a new mapping rule where you define your chaining servlet.
Let say /servlets/chainServlet for the virtual path and a comma separated list of servlets as srvA,srvB.
So when you invoke a request like http://localhost/servlets/chainServlet, internally the servlet srvA will be invoked first and its results will be piped into the servlet srvB.
The srvA servlet code should look like :


 public class srvA extends HttpServlet {
    ...
    public void doGet (...) {
      PrintWriter out =res.getWriter();
      rest.setContentType("text/html");
      ...
      out.println("Hello Chaining servlet");
    }
 }

All the servlet srvB has to do is to open an input stream to the request object and read the data into a BufferedReader object as for example :


 BufferedReader b = new BufferedReader( new InputStreamReader(req.getInputStream() ) );
 String data = b.readLine();
 b.close();

After that you can format your output with the data.
It should work straigthforward with Java Web Server or Jserv too. Just look at in their documentation to define an alias name. Hope that it'll help.

18) Why there are no constructors in servlets?

A servlet is just like an applet in the respect that it has an init() method that acts as a constrcutor. Since the servlet environment takes care of instantiating the servlet, an explicit constructor is not needed. Any initialization code you need to run should be placed in the init() method since it gets called when the servlet is first loaded by the servlet container.

19) How to handle multiple concurrent database requests/updates when using JDBC with servlets?

All the dbms provide the facility of locks whenever the data is being modified. There can be two scenarios:
  1. Multiple database updates on different rows, if you are using servlets the servlets will open multiple connections for different users. In this case there is no need to do additional programming.
  2. If database updates are on the same row then the rows are locked automatically by the dbms, hence we have to send requests to the dbms repeatatively until the lock is released by dbms.
This issue is dealt with in the JDBC documentation; look up "Transactions" and "auto-commit". It can get pretty confusing.

20) What is the difference between GenericServlet and HttpServlet?

GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets. Of course, it turns out that there's no such thing as FTP servlets, but they were trying to plan for future growth when they designed the spec. Maybe some day there will be another subclass, but for now, always use HttpServlet.

21) How do you share session objects between servlets and JSP?

Sharing sessions between a servlet and a JSP page is straight forward. JSP makes it a little easy by creating a session object and making it availabe already. In a servlet you would have to do it yourself. This is how:


 //create a session if one is not created already now
 HttpSession session = request.getSession(true);
 //assign the session variable to a value.
 session.putValue("variable","value");

in the jsp page this is how you get the session value:


 <%
 session.getValue("varible");
 %>

22) What is a servlet?

A servlet is a way of extending your web server with a Java program to perform tasks previously dealt with by CGI scripts or proprietary server extension frameworks.

23) Is there any method to unload a servlet from Web Server memory without restarting the server?

There is no standard method/mechanism to unload a servlet from memory. Some servers, like JWS, provide the means to load and unload servlets from their administration module. Others, like Tomcat, require you to just replace the WAR file.

24) What distinguishes a JavaBean from a Servlet?

JavaBeans are a set of rules to follow to create reusable software components, or beans. This contains properties and events. At the end you have a component which could be examined by a program (like an IDE) to allow the user of your JavaBean component to configure it and to run in its Java programs.
Servlets are Java classes running in a Servlet engine implementing a particular interface: Servlet, forcing you to implement some methods (service()). The servlet is an extension of your web server where this servlet is running on and only lets you know when a user requests a GET or POST calls from a web page to your servlet.
So, both have nothing in common except Java.

25) How much data we can store in a session object?

Any amount of data can be stored there because the session is kept on the server side.
The only limitation is sessionId length, which shouldn't exceed ~4000 bytes - this limitation is implied by HTTP header length limitation to 4Kb since sessionId may be stored in the cookie or encoded in URL (using "URL rewriting") and the cookie specification says the size of cookie as well as HTTP request (e.g. GET /document.html\n) cannot be longer then 4kb.

1 comment:

  1. Ive made over $8000 so far this month posting on facebook groups and with
    over 1 billion users theres plenty of money to go around, find out how
    I did

    it with my free guide http://cleanfiles.net/?y3dgQn4

    my homepage :: guide to make money on facebook

    ReplyDelete

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