JavaBeat FAQs
FAVORITES
Download a movie FAQ
JAVABEAT
Home
Articles
Tips
QnA
Forums
FAQs Topics Books Topic
Java Java Books
Struts Struts Books
Spring Spring Books
Hibernate Hibernate Books
JBoss Seam Seam Books
J2EE J2EE Books
EJB EJB Books
JSF JSF Books
Servlets Servlets Books
JDBC JDBC Books
RMI RMI Books
JMS JMS Books
JNI JNI Books
Design Patterns Patterns Books
Exception Exception Books
Apache Ant Ant Books
Groovy
Cobertura
Quartz

Java Servlets Interview Questions

Java Servlet is the serverside Java programming language. We can say it as serverside applet. How applet is used for writing the client side code, servlet is used for writing the serverside programming language. Servlet programming is first created by Sun Microsystems in June 1997. The latest version is Servlet 2.5 which is released with JEE 5.0 specification. Servlet is a specification and it can be implemented by anyone who can fulfil the mandatory requirements of the specification maintained by Sun.

Servlet Articles

What is servlet?

Servlet Life Cycle

New Features in Servlet 3.0

 
Servlets FAQs - 1 | Servlets FAQs - 2 | Servlets FAQs - 3 | Servlets FAQs - 4 | Servlets FAQs - 5
Servlets FAQs - 6 | Servlets FAQs - 7 | Servlets FAQs - 8 | Servlets FAQs - 9 | Servlets FAQs - 10

31) How can I get the absolute URL of a servlet/JSP page at runtime ?
 

You can get all the necessary information to determine the URL from the request object. To reconstruct the absolute URL from the scheme, server name, port, URI and query string you can use the URL class from java.net. The following code fragment will determine your page's absolute URL:

String file = request.getRequestURI();
if (request.getQueryString() != null) {
   file += '?' + request.getQueryString();
}
URL reconstructedURL = new URL(request.getScheme(),
                               request.getServerName(),
                               request.getServerPort(),
                               file);
out.println(URL.toString());

32) Why do GenericServlet and HttpServlet implement the Serializable interface?
 

GenericServlet and HttpServlet implement the Serializable interface so that servlet engines can "hybernate" the servlet state when the servlet is not in use and reinstance it when needed or to duplicate servlet instances for better load balancing. I don't know if or how current servlet engines do this, and it could have serious implications, like breaking references to objects gotten in the init() method without the programmer knowing it. Programmers should be aware of this pitfall and implement servlets which are stateless as possible, delegating data store to Session objects or to the ServletContext. In general stateless servlets are better because they scale much better and are cleaner code.

33) How does one choose between overriding the doGet(), doPost(), and service() methods?
 

The differences between the doGet() and doPost() methods are that they are called in the HttpServlet that your servlet extends by its service() method when it recieves a GET or a POST request from a HTTP protocol request.

A GET request is a request to get a resource from the server. This is the case of a browser requesting a web page. It is also possible to specify parameters in the request, but the length of the parameters on the whole is limited. This is the case of a form in a web page declared this way in html: <form method="GET"> or <form>.

A POST request is a request to post (to send) form data to a resource on the server. This is the case of of a form in a web page declared this way in html: <form method="POST">. In this case the size of the parameters can be much greater.

The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are (you must do the parsing yourself).

The HttpServlet instead has doGet() and doPost() methods that get called when a client request is GET or POST. This means that the parsing of the request is done by the servlet: you have the appropriate method called and have convenience methods to read the request parameters.

NOTE: the doGet() and doPost() methods (as well as other HttpServlet methods) are called by the service() method.

Concluding, if you must respond to GET or POST requests made by a HTTP protocol client (usually a browser) don't hesitate to extend HttpServlet and use its convenience methods.
If you must respond to requests made by a client that is not using the HTTP protocol, you must use
service().

34) How do servlets differ from RMI? What are the advantages and disadvantages of each technology?
 

Servlets extend the server-side functionality of a website. Servlets communicate with other application(s) on that server (or any other server) and perform tasks above and beyond the "normal" static HTML document. A servlet can receive a request to get some information through EJB from one or more databases, then convert this data into a static HTML/WML page for the client to see, for example. Even if the servlet talks to many other applications all over the world to get this information, it still looks like it happened at that website.

RMI (Remote Method Invocation) is just that - a way to invoke methods on remote machines. It is way for an application to talk to another remote machine and execute different methods, all the while appearing as if the action was being performed on the local machine.

Servlets (or JSP) are mainly used for any web-related activity such as online banking, online grocery stores, stock trading, etc. With servlets, you need only to know the web address and the pages displayed to you take care of calling the different servlets (or actions within a servlet) for you. Using RMI, you must bind the RMI server to an IP and port, and the client who wishes to talk to the remote server must know this IP and port, unless of course you used some kind of in-between lookup utility, which you could do with (of all things) servlets.

35) How can we use a servlet as a proxy for communications between two applets?

One way to accomplish this is to have the applets communicate via TCP/IP sockets to the servlet. The servlet would then use a custom protocol to receive and push information between applets. However, this solution does have firewall problems if the system is to be used over and Internet verses an Intranet.

36) How can I design my servlet/JSP so that query results get displayed on several pages, like the results of a search engine? Each page should display, say, 10 records each and when the next link is clicked, I should see the next/previous 10 records and so on.
 

Use a Java Bean to store the entire result of the search that you have found. The servlet will then set a pointer to the first line to be displayed in the page and the number of lines to display, and force a display of the page. The Action in the form would point back to the servlet in the JSP page which would determine whether a next or previous button has been pressed and reset the pointer to previous pointer + number of lines and redisplay the page. The JSP page would have a scriplet to display data from the Java Bean from the start pointer set to the maximum number of lines with buttons to allow previous or next pages to be selected. These buttons would be displayed based on the page number (i.e. if first then don't display previous button).

37) How do I deal with multi-valued parameters in a servlet?
 

Instead of using getParameter() with the ServletRequest, as you would with single-valued parameters, use the getParameterValues() method. This returns a String array (or null) containing all the values of the parameter requested.

38) How can I pass data retrieved from a database by a servlet to a JSP page?
 

One of the better approaches for passing data retrieved from a servlet to a JSP is to use the Model 2 architecture as shown below:

Basically, you need to first design a bean which can act as a wrapper for storing the resultset returned by the database query within the servlet. Once the bean has been instantiated and initialized by invoking its setter methods by the servlet, it can be placed within the request object and forwarded to a display JSP page as follows:

  com.foo.dbBean bean = new com.foo.dbBean();
  //call setters to initialize bean
  req.setAttribute("dbBean", bean);
  url="..."; //relative url for display jsp page
  ServletContext sc = getServletContext();
  RequestDispatcher rd = sc.getRequestDispatcher(url);
  rd.forward(req, res);

The bean can then be accessed within the JSP page via the useBean tag as:

<jsp:useBean id="dbBean" class="com.foo.dbBean" 
  scope="request"/>
...
<%
  //iterate through the rows within dbBean and
  //access the values using a scriptlet
%>

Also, it is best to design your application such that you avoid placing beans into the session unless absolutely necessary. Placing large objects within the session imposes a heavy burden on the performance of the servlet engine. Of course, there may be additional design considerations to take care of - especially if your servlets are running under a clustered or fault-tolerant architecture.

39) How can I use a servlet to generate a site using frames?
 

In general, look at each frame as a unique document capable of sending its own requests and receiving its own responses. You can create a top servlet (say, FrameServlet) that upon invocation creates the frame layout you desire and sets the SRC parameters for the frame tags to be another servlet, a static page or any other legal value for SRC.

---------------------- SAMPLE ----------------------
 
  public void doGet(HttpServletRequest request,
     HttpServletResponse response) throws ServletException, IOException {                                               
    response.setContentType("text/html");                                
    PrintWriter out = new PrintWriter (response.getWriter());        
 
    out.println("<html>");
    out.println("<head>Your Title</head>");
 
    // definingthe three rows of Frames for the main page
    // top      : frm_1
    // middle : frm_2
    // bottom : frm_3
 
    out.println("<frameset rows=12%,70%,* cols=*>");
    out.println("<frame src=/servlets/MenuServlet                name=frm_1>");
    out.println("<frame src=/servlets/DummyServlet?mode=full     name=frm_2>");
    out.println("<frame src=/servlets/DummyServlet?mode=small  name=frm_3>");
    out.println("</frameset>");
 
    out.println("<body>");
    out.println("</body></html>");
    out.close();
-------------------------- END ------------------------------------------

Where MenuServlet and DummyServlet provide content and behavior for the frames generated by FrameServlet.

40) What is HTTP tunneling, in the general sense?
 

HTTP tunneling is a general technique whereby arbitrary data may be sent via an HTTP connection to and from CGI scripts or Java Servlets on a Web server. This is done by serializing the data to be transmitted into a stream of bytes, and sending an HTTP message with content type "application/octet-stream".

HTTP tunneling is also referred to as Firewall tunneling.

Related Articles
JAX-WS Web Services in NetBeans 6.1
JPA in NetBeans 6.1
EJB 3.0 and WebServices
Types of Managed Bean scopes in Spring Framework
OpenCms 7 Development
Liferay Portal Enterprise Intranets
ZK Developer’s Guide : Online Media Library
The BIRT Environment and Your First Report
AJAX - The Complete Reference
The Java 6.0 Compiler API
more articles
java6 ejb3 jsf hibernate eclipse ajax groovy spring seam java struts webservice j2me guice java5 jca tapestry soa linux ria books

Favorites
Buy movies
Access Control
Busby seo challenge contest
Sohbet
Chat
Webmaster Hosting Forum
Java Jobs
MyVideoLib
India News
Internet Advances
Sohbet
chat
Latest QnA
SCJD Tips
When we start a thread by applying start() method on it ,how does it knows that to execute run()method?
About Wrapper class in Java
How to configure weblogic 7.0 in MyEclipse?
Static Block and Static Initializer in Java

JavaBeat Website (2004-2008), India
javabeat | about us | planetoss
Copyright (2004 - 2008), JavaBeat