Java Servlets FAQ's

How do I set my CLASSPATH for servlets?
For developing servlets, just make sure that the JAR file containing javax.servlet.* is in your CLASSPATH, and use your normal JAVAC to compile servlet.

Incase of Tomcat 4.x, you must set classpath to tomcat/common/lib/servlet.jar. Incase of Tomcat 5.x, you must set classpath to tomcat/common/lib/servlet-api.jar

Note: Please check the documentation of the Server you are using for exact location and .jar file name.

To run servlet, you need not set any classpath since Server (like Tomcat) is already having access to the required .jar files.

How do I support both GET and POST protocol from the same Servlet?
The easy way is, just write code for POST, then have your doGet method call your doPost method.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
	doPost(req, res);
}

How do I use Session Tracking? That is, how can I maintain "session scope data" between servlets in the same application?
Session Tracking is one of the most powerful features of Servlets and JSP. Basically, the servlet engine takes care of using Cookies in the right way to preserve state across successive requests by the same user. Your servlet just needs to call a single method getSession() and it has access to a persistent hashtable of data that's unique to the current user.

How can my applet or application communicate with my servlet?
It's pretty straightforward. You can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection to the web server. The server then passes this information to the servlet in the normal way.

Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.

Of course, you can write a servlet that is meant to be called only by your applet, in which case it *does* know the difference. You can also open a ServerSocket on a custom TCP port, and have your applet open a Socket connection. You must then design and implement a custom socket-level protocol to handle the communication. This is how you could write, e.g., a Chat applet communicating with a servlet. In general, a custom protocol requires more work than HTTP, but is more flexible. However, custom protocols have a harder time getting through firewalls.

How do I create an image (GIF, JPEG, etc.) on the fly from a servlet
Once you have an image file in your servlet, you have two choices:
  1. Write the file to disk and provide a link to it. Make sure you write it to a location that's in your web server directory tree (not just anywhere on the server's disk).
  2. Output the image directly from the servlet.You do this by setting the Content-type header to image/gif (for GIFs), or image/jpeg (for JPEGs). You then open the HttpResponse output stream as a raw stream, NOT as a PrintStream, and send the bytes directly down this stream using the write() method.

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,
 <FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet' >
 <INPUT TYPE='file' NAME='mptest' >
 <INPUT TYPE='submit' VALUE='upload' >
 </FORM>
 
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.

How do I access a database from my servlet or JSP?
JDBC allows you to write SQL queries as Java Strings, pass them to the database, and get back results that you can parse.

To access database from your servlet, make sure JDBC driver for the database you are accessing is accessible to Web Server (Tomcat).

For example, in Tomcat to access Oracle database through JDBC driver for Oracle, you need to place classes111.zip (renamed to classess111.jar) or classes12.jar in /WEB-INF/lib directory of the application or /common/lib directory of Tomcat.

How does a servlet communicate with a JSP page?
A servlet can send data to JSP in the following ways.
  1. 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, test.jsp, by means of a request dispatcher. This method can be used for any kind and any amount of data.
    public void doPost (HttpServletRequest request, HttpServletResponse response)
    {
    	try
    	{
    		demo.FormBean f = new demo.FormBean();
    		String name = request.getParameter("name");
    		f.setName(request.getParameter("name"));
    		request.setAttribute("fBean",f);
    		request.getRequestDispatcher("test.jsp").forward(request, response);
     	}
     	catch (Exception ex)
     	{
    
     	}
      }
    

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

     <jsp:useBean id="fBean" class="demo.FormBean" scope="request"/>
     <jsp:getProperty name="fBean" property="name" />
     
  2. Second method is to pass data as parameter along with URL. This can be used only when simple data is to be sent from servlet to JSP.
    public void doPost (HttpServletRequest request, HttpServletResponse response)
    {
       String name;
       // get name from database or some other source
       response.sendRedirect("test.jsp?name='" + name+ "'");  // for example, test.jsp?name='pragada srikanth'
     }
    

    The JSP page test.jsp can then read the value from parameter as follows:

    
    <%
    String name;
      name =  request.getParameter("name");
    %>
    
    
    
Q: 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 synchronization for your variables. The key however, is to effectively minimize the amount of code that is synchronized 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.

Can I invoke a JSP error page from a servlet?
Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute.

How can I download a file (for instance, a Microsoft Word document) from a server using a servlet and an applet?
Try telling the applet to call getAppletContext().showDocument()

In case or servlet, provide an anchor tag pointing to file that is to be downloaded.

out.println("<a href=document1.doc>Document</a>");

Can I call a JSP, then have it return control to the original JSP, like a subroutine or method call?
Yes. That is exactly the purpose served by the <jsp:include> action. The syntax of the include action is:

      <jsp:include page="relativeURL" flush="true" />
 

How can I download files from a URL using HTTP?
One way to do this is by using a URLConnection to open a stream to your desired URL, then copy the data out of the stream to a file on your local file system.

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

What is a servlet engine?
A "servlet engine" is a program that plugs in to a web server and runs servlets. The term is obsolete; the preferred term now is "servlet container" since that applies both to plug-in engines and to stand-alone web servers that support the Servlet API.

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.

In short GenericServlet is protocol independent, whereas HttpServlet is protocol dependent Generic servlet is used for small data transfer whereas HttpServlet is used for huge data transfer.

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.

What is a servlet bean?
A servlet bean is a serializable servlet that follows the JavaBeans component architecture, basically offering getter/setter methods.

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.

The contents of the WEB-INF directory are: /WEB-INF/web.xml deployment descriptor /WEB-INF/classes/* directory for servlet and utility classes. The classes in this directory are used by the application class loader to load classes from. /WEB-INF/lib/*.jar area for Java ARchive files which contain servlets, beans, and other utility classes useful to the web application. All such archive files are used by the web application class loader to load classes from.

What is a WAR file and how do I create one?
WAR (or "web archive") file is simply a packaged webapp directory. It is created using the standard Java jar tool.

For example: jar cf ../mywebapp.war *

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

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 :

How do I get the name of the currently executing script?
Use request.getRequestURI() or req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info.

The following example demonstrates it:

 URL  http://www.host.com/servlets/HelloEcho/extra/info?height=100&width=200

 getRequestURI   /servlets/HelloEcho/extra/info
 getServletPath  /servlets/HelloEcho
 getPathInfo     /extra/info
 getQueryString  height=100&width=200
 

This is useful if your form is self-referential; that is, it generates a form which calls itself again.
For example:

 out.println("<FORM METHOD=POST ACTION=\"" + request.encodeURL(req.getServletPath()) + "\">");
 out.println("<INPUT NAME=value>");
 out.println("<INPUT TYPE=submit>");
 out.println("</FORM>");
Note: encodeURL() adds session information if necessary.