CSS font stacks, developer FAQs & web standards

Your banner ad here

WestNIC provides reliable web hosting services

Top Canadian Hotels no booking fees from Victoria BC to Nova Scotia

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.

Servlet concepts

Q: What's the difference between applets and servlets?

A: There are many fundamental differences between Applet and Servlet classes, the Java API documentation for the two types will show you they have little in common.

Applets are essentially graphical user interface (GUI) applications that run on the client side in a network environment, typically embedded in an HTML page. Applets are normally based on Abstract Windowing Toolkit components to maintain backward-compatibility with the widest range of browsers' Java implementations. The application classes are downloaded to the client and run in a Java Virtual Machine provided by the browser, in a restrictive security environment called a "sandbox".

Servlets are used to dynamically generate HTTP responses and return HTML content to Web browsers on the server side. Servlets are often used to validate and process HTML form submissions and control a series of user interactions in what is known as a Web application. Servlets can be used to control all aspects of the request and response exchange between a Web browser and the server, called a servlet container.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Do we open servlet classes directly instead of HTML?

A: Servlets are used to deliver HTML to Web browsers, but they are not like static HTML documents. When you set up a servlet in a Web application it has a URL like a static HTML document, so you can link to it, bookmark it or send the URL by email, just as you would with an standard Web page. The main difference is that the HTML sent to the Web browser is composed dynamically by the servlet and its contents can be customised based on the details of the request sent by the Web browser.

When you open a servlet URL the browser does not display content of the servlet class, but a dynamic HTML document created by the servlet. The servlet class is written as a standard Java class that extends the HttpServlet class. In its most basic form, the HTML output can be created by a series of print() statements on a PrintWriter. The method that handles simple Web requests is called doGet(), as below.

public final void doGet(HttpServletRequest request,
                        HttpServletResponse response)
    throws IOException {

    PrintWriter output = response.getWriter();

    output.println("<html>");
    output.println("  <head>");
    output.println("    <title>");

    // Other HTML output

    output.flush();
    output.close();
}
    

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What part of the Java platform do servlets and JSP belong to?

A: The servlet and JSP APIs are a standard extension to the core Java API and runtime system. Their package names are prefixed javax to indicate they are standard extensions, but that means that they rely upon a code implementation provided by a specific vendor.

For example, the Apache Tomcat project supplies its own implementation of the servlet and JSP API that is integrated with the servlet container. Developers must compile their code using the vendor's servlet package implementation by including it in the compiler's classpath. The servlet container includes the same package classes in its runtime system and feeds concrete instances of the servlet interface types to the servlet's lifecycle methods.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How does the JVM execute a servlet compared with a regular Java class?

A: Servlets are standard Java classes and are executed by the Java Virtual Machine in exactly the same way as any other. However, the environment or context in which servlets are executed is different. A servlet is not invoked directly through a main method, the class is loaded and run by a servlet container.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
How does the JVM execute a servlet compared with a regular Java class?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I tell when a servlet is instantiated?

A: A servlet must be instantiated before it is brought into service by the servlet container, so one way to check is to make a request to the servlet and check the response. If you need to check indirectly, you can override the init(ServletConfig) method and add log(String) statements to it. This method is called after the servlet container has instantiated the servlet before it is brought into service.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Servlet programming

Q: How can I write a servlet using Javascript?

A: Java servlets is a server side technology that delivers dynamic content to Web browsers and other clients. Javascript is also delivered by a Web server, but the code is only interpreted and executed after it has been downloaded by the Web browser. This means that it is not possible to write servlet code in Javascript.

It is possible to include Javascript in the output of servlets and Java Server Pages, just like standard Web pages. It is also possible to dynamically generate Javascript using a servlet and use it as the source for a script tag, though this is only advisable in rare cases.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I use a normal class to handle my requests?

A: Servlets are normal Java classes, they compile and run just like any other class. All that is required is that servlets implement the javax.servlet.Servlet interface. Usually, they extend a protocol-specific class such as javax.servlet.http.HttpServlet.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
Can I use a normal class to handle my requests?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I include normal Java classes in servlets?

A: Any Java class can be used in a Web application, provided you make the classes available to the servlet container at runtime. The Java API classes can be used directly by adding import statements to your servlet class. Other supporting classes can also be imported, but these classes must be added to the classes or lib directory of your application.

If you need to configure the supporting classes, this can be done with standard servlet configuration features using the ServletConfig and ServletContext objects available to the init(ServletConfig) method.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I use a constructor in my servlet?

A: A servlet is a normal Java class, so when there are no custom constructors, there is an implicit default constructor with no arguments. Servlet containers typically use the Class.newInstance() method to load servlets, so you must be careful to add an explicit default constructor if you add non-default constructors.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
Can I use a constructor in my servlet?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What happens if I add a main method to my servlet?

A: It is possible to write a main method for a servlet, but it will not be called by the servlet container, it is not part of the servlet lifecycle process. If you invoke your servlet through the main method using the java command it will behave exactly like a standard Java class, it cannot operate as a Web application in its own right and cannot be addressed using HTTP requests. Servlets must run in a servlet container to deliver Web applications as intended.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Servlet start up

Q: How do I compile a servlet?

A: To compile a servlet, you will need to have the Java Servlet API classes in your classpath. Most Java servlet containers come with a copy, it may be called servlet.jar or something similar. The basic classes are in the packages javax.servlet and javax.servlet.http.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
How do I compile a servlet?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Why won't my servlet compile?

A: All those "cannot find symbol" error messages mean that you do not have the Java servlet JAR file on your compiler's classpath, so it cannot find the servlet class files. The servlet JAR file is normally distributed with your servlet container. For Apache Tomcat it is a file named {CATALINA_HOME}/common/lib/servlet-api.jar. Add this to your compiler classpath as follows.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
Why won't my servlet compile?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Where is the servlet stored and where does it run?

A: When you create a servlet, the code must be installed in a servlet container which operates as an HTTP server application. In the a development environment the servlet container is often installed on a developer's own workstation, or a hardware server in the local network where it can be accessed privately for testing. In a production environment the servlet container is usually installed on a server that is accessible from the Internet, but the Java software arrangement is basically the same.

Servlet code is compiled to Java class byte code which is physically located on the server hardware with the servlet container. The servlet operates as an extension of the servlet container and its code is executed on the server. Web browsers operate as clients which connect to the servlet container, issue HTTP requests and receive HTTP responses from the servlet container, mostly in the form of HTML pages and other Web content. The servlet code is not downloaded or executed by the Web browser at all, it only receives standard Web content and renders it accordingly.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What are the basic steps to run a servlet?

A: The key steps in creating and running a servlet are outlined below in the simplest form. There are different techniques that can be used to complete these stages, described in other FAQ answers.

  1. Write and compile your servlet, e.g. ExampleServlet.class
  2. Create a Web application directory structure under the webapp directory of your servlet container (or use an existing one), e.g.
    {webapps-dir}/example
    {webapps-dir}/example/WEB-INF
    {webapps-dir}/example/WEB-INF/classes
              
  3. Place your servlet class file in the WEB-INF/classes directory for your application, e.g.
    {webapps-dir}/example/WEB-INF/classes/ExampleServlet.class
              
  4. Create a WEB-INF/web.xml file for your application (or edit an existing one) and add servlet and servlet-mapping elements for your servlet, e.g.
    {webapps-dir}/example/WEB-INF/web.xml
              
  5. Start the servlet container.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What is the difference between JAR and WAR files?

A: There is no difference between the binary form of JAR and WAR files, they both use zip compression provided by the jar tool. You can create a WAR file by navigating to the root directory of your Web application and typing the jar command, as below.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
What is the difference between JAR and WAR files?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Servlet techniques

Q: Can I access a servlet from a stand alone client?

A: It is certainly possible to access a servlet that is hosted in a servlet container. Any HTTP client should be able to connect to a properly configured servlet container and make requests to a servlet. However, servlets do not run in their own right, they are not server applications.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I write a servlet client for testing?

A: Marty Hall provides the source code for a basic HTTP client in his book Core Servlets and Java Server Pages. The source code for chapter 3 is available online. Look for WebClient.java and supporting classes. This application allows you to manually input the host, request path, HTTP header values and view the headers returned by a Web application.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What is URL-rewriting?

A: URL-rewriting is a way of maintaining a session between an HTTP client and a servlet container which does not use cookies. Rather than exchange a session ID in a cookie, the servlet container includes it in the hyperlink URLs it generates for servlets and JSP.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
What is URL-rewriting?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What's the difference between forward, include and redirection?

A: The RequestDispatcher forward() and include() methods are mechanisms that are internal to a servlet container and do not affect the public URL of a Web resource. When you call the forward() method on a RequestDispatcher with a JSP path, the servlet container returns the JSP content on the original servlet's URL; this effectively becomes the response of the servlet itself.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
What's the difference between forward, include and redirection?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Add this page to your chosen social bookmarking service

Style warning, please read

Home · CSS · Java · Javascript · HTML · Help · Log