JavaBeat FAQs
SPONSORS
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

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

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.)

  1. 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.

  1. 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.

  1. 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:

    <form method="POST" action="j_security_check">
      <input type="text" name="j_username">
      <input type="password" name="j_password">
    </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 <jsp:forward page="/relativepath/YourServlet" /> or response.sendRedirect("http://path/YourServlet").

Variables can be sent as:

<jsp:forward page=/relativepath/YourServlet>
<jsp:param name="name1" value="value1" />
<jsp:param name="name2" value="value2" />
</jsp:forward>

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:

<web-app>
    <servlet>
        <servlet-name>
            myServlet
        </servlet-name>
        <servlet-class>
            myServlet
        </servlet-class>
    </servlet>
        <servlet-mapping>
            <servlet-name>
                myServlet
            </servlet-name>
            <url-pattern>
                /jsp-bin/*
            </url-pattern>
        </servlet-mapping>
</web-app>

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.

Related Articles
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
Spring Web Flow - Introduction
Introduction to Spring Web Framework
Integrating Struts With Spring
What's new in Struts 2.0? - Struts 2.0 Framework
more articles
java6 ejb3 jsf hibernate eclipse ajax groovy spring seam java struts webservice j2me guice java5 jca tapestry soa linux ria books

Sponsors
Webmaster Hosting Forum
Java Jobs
MyVideoLib
India News
Internet Advances
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 Media (2004-2008), India
javabeat | planetoss | links directory | advertise
Copyright (2004 - 2008), JavaBeat