JavaTM Servlets provide web developers with a simple, consistent mechanism for extending the functionality of a web server and for accessing existing business systems. A servlet can almost be thought of as an applet that runs on the server side -- without a face. Java Servlets have made many web applications possible.
Servlets are the Java platform technology of choice for extending and enhancing Web servers. Servlets provide a component-based, platform-independent method for building web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), Servlets are server- and platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools.
Written in Java, Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets also access library of HTTP-specific calls, and all the benefits of the mature Java language, including portability, performance, reusability, and crash protection.
Today, Servlets are a popular choice for building interactive web applications. Third-party Servlet containers are available for Apache Web Server, iPlanet Web Server (formerly Netscape Enterprise Server), Microsoft IIS, and others. Servlet containers can also be integrated with web-enabled application servers, such as BEA WebLogic Application Server, IBM WebSphere, Netscape Application Server, and others.
You might want to check out the latest information on JavaServer PagesTM (JSP). JSP technology is an extension of the servlet technology created to support authoring of HTML and XML pages. It makes it easier to combine fixed or static template data with dynamic content. Even if you're comfortable writing servlets, there are several compelling reasons to investigate JSP technology as a complement to your existing work. For more information on writing JSPs, see "Developing JavaServer Pages (JSP)".
For more information on all things Servlet, visit Sun's Java software site at http://java.sun.com/products/servlet/index.html.
JBuilder provides several methods for developing servlets.
This topic discusses using the Servlet wizard, which simplifies the creation of servlets by generating a beginning template and supporting files.
This topic discusses using InternetBeans Express components to generate HTML code which can be used with servlets and JSPs to insert dynamic data into a predesigned web page.
This topic discusses how to enable an application to connect CORBA objects to HTML forms . The mechanism you use to link the controls to CORBA objects is the <SERVLET> tag.
Other Servlet tutorials are located on the Sun Microsystems Web site at http://jserv.java.sun.com/products/java-server/documentation/webserver1.1/servlets/servlet_tutorial.html.
Sun Microsystems has delivered the latest versions of JavaServer PagesTM (JSP) and Servlets source code to the Apache Software Foundation http://www.apache.org to be developed and released under the Apache development process as the official JSP 1.1/Servlets 2.2 reference implementation. Apache, Sun, and a variety of other companies and individuals are openly developing a robust Reference Implementation that is freely available to any company or individual. This reference implementation, developed under the project name Jakarta and code-named Tomcat, will be the only reference implementation available. This implementation is available to any company or developer to be used in Web servers, development tools, and to create dynamic, interactive Web sites. JBuilder delivers Tomcat "in the box" to use as your Web server so that you can successfully develop and test your JSPs and Servlets within the JBuilder development environment.
javax.HTTPServlet
. The JBuilder Servlet wizard generates servlets of the following content type:
The following steps provide an outline of steps necessary to develop the different types of servlets. For a tutorial that creates a simple HTML servlet, see "Tutorial: Creating a servlet using the Servlet wizard."
If all defaults are accepted, files named Servlet1.java
and Servlet1.shtml
will be added to your project. The Enable Web Run/Debug From Context Menu option is automatically set for the Servlet1.java
file to enable you to run the servlet independent of the SHTML file. For a description of the options available in the Servlet wizard, see Servlet wizard options.
The generated, default Servlet1.java
file that defines the servlet looks like this:
package untitled1; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class Servlet1 extends HttpServlet { private static final String CONTENT_TYPE = "text/html"; /**Initialize global variables*/ public void init(ServletConfig config) throws ServletException { super.init(config); } /**Process the HTTP Get request*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<font color=\"green\">"); out.println("<p>The servlet has received a GET. This is the reply.</p>"); out.println("</font>"); } }
Servlet1.shtml
, that can also launch the servlet looks like this:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> <title> Servlet1 </title> </head> <body> <p>launches servlet Servlet1</p> <servlet codebase="" code="untitled1.Servlet1.class" > </servlet> <p><a href="/servlet/untitled1.Servlet1"> Click here to call Servlet: Servlet1</a></p> </body> </html>
Servlet1.java
file. For example, the simple servlet tutorial in this chapter adds code to count the number of visitors to a site.
Servlet1.java
, and select Make. Compilation errors are displayed in the lower pane.
To debug servlets, set a breakpoint, and then choose Debug from the context menu. This starts the Servlet engine, in this case Tomcat, in debug mode, configured so that it can see the project's HTML and servlets, and switches the IDE into a Web View browser so that you can see the output.
Servlet1.java
file, select Web Run.
The program runs: two new tabs appear in the content pane for the servlet: Web View and Web View Source. These tabs display the output from the running servlet in raw HTML and in parsed HTML. If you made no modifications to the Servlet wizard, clicking the link sends a GET request to the servlet, and the reply appears in the Web View browser.
When you select File|New, then select Servlet from the New page of the Object Gallery, the Servlet wizard appears to make the creation, debugging, and testing of servlets easy!
On the first page of the Servlet wizard, you can enter the Package to which you want the servlet to belong, and name the servlet in the Class field. In the first step of the Servlet wizard, the Generate Content Type and Implement Methods fields require further discussion.
The options for Generate Content Type include:
The files generated when HTML is selected are shown in "Overview: Creating a servlet using the Servlet wizard."
Files with the same names as those generated for the HTML option are generated. In the Servlet1.java
file, a line of code indicating that the DOC TYPE is XHTML is added, and looks like this:
private static final String DOC_TYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" + " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">";
Similar text is added to the top of the SHTML file, if it was generated.
The Servlet1.java
file is generated. There is no option for an SHTML file with a WML-type servlet. The Servlet1.java
file is similar to the one generated for an HTML-servlet, but a line of code indicating that the DOC TYPE is WML and the CONTENT TYPE is WAP is added, and looks like this:
private static final String CONTENT_TYPE = "text/vns.wap.wml"; private static final String DOC_TYPE = "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n" + " \"http://www.wapforum.org/DTD/wml12.dtd\">";
Code to run the servlet's GET request as a WML-servlet is added as well, and looks like this:
out.println("<?xml version=\"1.0\"?>"); out.println(DOC_TYPE); out.println("<wml>"); out.println("<card>"); out.println("<p>The servlet has received a GET. This is the reply.</p>"); out.println("</card></wml>");
The file Servlet1.java
is generated. The step to create an SHTML file is eliminated, because this option is not valid. The Servlet1.java
file includes code to identify the servlet as an XML-servlet, and looks like this:
private static final String CONTENT_TYPE = "text/xml";
The servlet's doGet()
method is modified from the HTML version with the following code:
out.println("<?xml version=\"1.0\"?>"); if (DOC_TYPE != null) { out.println(DOC_TYPE); }
This option of the Servlet wizard provides options for overriding the standard servlet methods. HttpServlet
provides an abstract class that you can subclass to create an HTTP servlet, which receives requests from and sends responses to a Web iste. When you subclass HttpServlet
, you must override at least one method, usually one of these. For more information on the methods, refer to the Servlet documentation at http://java.sun.com/products/servlet/index.html. The methods generated when HTML is the content type look like this:
doGet()
- override this method if the servlet supports HTTP GET requests. The GET method allows a client to read information from the Web server, passing a query string appended to an URL to tell the server what information to return.
/**Process the HTTP Get request*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<font color=\"green\">"); out.println("<p>The servlet has received a GET. This is the reply.</p>"); out.println("</font>"); }
doPut()
- override this method if the servlet supports HTTP PUT requests. The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.
/**Process the HTTP Put request*/ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
doPost()
- override this method if the servlet supports HTTP POST requests. The HTTP POST method allows the client to send data of unlimited length to the Web server once and is useful when posting information such as credit card numbers.
/**Process the HTTP Post request*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>htmlservlet</title> </head>"); out.println("<body>"); out.println("<p>The servlet has received a POST. This is the reply.</p>"); out.println("</body></html>"); }
doDelete()
- override this method if the servlet supports HTTP DELETE requests. The DELETE operation allows a client to remove a document or Web page from the server.
/**Process the HTTP Delete request*/ public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
The second step of the Servlet wizard is the SHTML file details page if you selected either HTML or XHTML from the Generate Content Type option. With JBuilder and the Tomcat servlet engine, you can run a servlet directly from the Servlet1.java
file. When the servlet is created using the Servlet wizard, the Java properties option to Enable Web Run/Debug From Context Menu is turned off (to see this, right-click on the Java file, and select Properties from the context menu). If you want to run the servlet directly, as described in "Invoking a servlet from a browser window," unselect the Generate SHTML File option here.
If you want to call the servlet from an HTML page, as described in "Calling servlets from an HTML page," leave this option selected. An SHTML file, such as that shown in "Overview: Creating a servlet using the Servlet wizard," with the same name as the servlet, is added to the project when this option is selected.
When HTML or XHTML are the content types, this is Step 3. If WML or XML are selected, this is Step 2. This page allows you to enter servlet parameters. For example, in the servlet tutorial, "Tutorial: Creating a servlet using the Servlet wizard," a parameter of type String is created to allow entry of the user's name. Servlet URLs can take the parameter as a query, for example, the simple servlet created in the tutorial can be run by entering the following URL for the servlet:
http://localhost:8080/servlet/firstServlet.firstServlet?userName=Honey
The following topics discuss a few ways to invoke servlets:
Servlets can be called directly by typing their URL into a browser's location window. The general form of a servlet URL, where servlet-file-name corresponds to the name you have given the servlet, is:
http://machine-name:port-number/servlet/servlet-file-name
For example, an URL in the format of any of the following examples should enable you to run the servlet:
Servlet URLs can contain queries, such as for HTTP GET requests. For
example, the servlet in the tutorial takes the
user name as a query. The servlet's name is
firstServlet
; the URL for the servlet to get and display the user name is:
http://localhost:8080/servlet/firstServlet.firstServlet?userName=John
To invoke a servlet from within an HTML page just use the servlet URL in the appropriate HTML tag. Tags that take URLs include those that begin anchors and forms, and meta tags. Servlet URLs can be used in HTML tags anywhere a normal URL can be used, such as the destination of an anchor, as the action in a form, and as the location to be used when a META tag directs that a page be refreshed. This section assumes knowledge of HTML. If you don't know HTML you can learn about it through various books or by looking at the HTML 3.2 Reference Specification on the Web at http://www.w3c.org/TR/REC-html32.html.
For example, in the default servlet created in the overview section in this chapter, the SHTML page contains an anchor with a servlet as a destination:
<a href="/servlet/untitled1.Servlet1">Click here to call Servlet: Servlet1</a><BR>
The HTML pages also regularly use the following tags to invoke servlets:
<form action="http://localhost:8080/servlet/firstServlet.firstServlet method="post">
http-equiv
attribute.
<meta http-equiv="refresh" content="4; url=http://localhost:8080/servlet/Servlet1;">
To have your servlet call another servlet,
This section addresses the second option. To call another servlet's public methods directly, you must:
Servlet
object.
public
methods
To gain access to the Servlet
object, use the
ServletContext
object's getServlet
method. Get
the ServletContext
object from the ServletConfig
object stored in the Servlet
object.
Once you have the servlet object, you can call any of that servlet's public methods.
You must exercise caution when you call another servlet's methods. If
the servlet that you want to call implements the SingleThreadModel
interface, your call could violate the
called servlet's single threaded nature. (The server has no way to
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 of the other servlet instead of calling the other servlet's methods directly.
To demonstrate how to develop a Java servlet, we will build a fairly basic Hello World-type application that illustrates the general servlet framework. This first servlet will display a welcome message, the user's name, and the number of connections since the servlet was started.
All servlets are built by extending a basic Servlet
class and defining Java methods to deal with incoming connections. This sample servlet will extend the HttpServlet
class that understands the Web's HTTP protocol and handles most of the underlying "plumbing" required for a Web application.
To build firstServlet
, we extend the base HttpServlet
class and define a method to output several lines of HTML, including the user's name.
To develop the sample Hello World servlet in JBuilder,
The Servlet wizard starts.
doPost()
method (the doGet()
method should already be selected).
Name* | UserName |
Type* | String |
Desc | Name of User |
Variable* | userName |
Default | Hey You |
firstServlet.java
and firstServlet.shtml
are added to the project. The Servlet library is added to the Project Properties.
package firstservlet; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class firstServlet extends HttpServlet { private static final String CONTENT_TYPE = "text/html"; /**Initialize global variables*/ int connections; public void init(ServletConfig config) throws ServletException { super.init(config); connections=0; } /**Process the HTTP Get request*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<font color=\"green\">"); out.println("<p>The servlet has received a GET. This is the reply.</p>"); out.println("</font>"); } /**Process the HTTP Post request*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Name of User String userName = "Hey you"; try { userName = request.getParameter("UserName"); } catch(Exception e) { e.printStackTrace(); } response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>firstServlet </title></head>"); out.println("<body>"); out.println("<p>The servlet has received a POST. This is the reply.</p>"); out.println("<p>Thanks for visiting, "); out.println(request.getParameter("UserName")); out.println("<P>"); out.println("Hello World - my first Java Servlets program!"); out.println("<P>You are visitor number "); connections++; out.println(Integer.toString(connections)); out.println("</body></html>"); } }
To compile the servlet, first set the runtime properties. To do this,
To compile and debug the servlet,
firstServlet.shtml
.
The project compiles. Compilation errors are displayed in the lower pane.
To run the servlet,
firstServlet.shtml
.
Running the servlet starts Tomcat, the reference implementation of Servlet 2.2/JSP 1.1, done by the Apache Software Foundation, as part of its Jakarta project. Using Tomcat, you can run and debug servlets and JSP's. The output from Tomcat will appear on a new output pane in the lower part of the JBuilder IDE. Output from servlets or beans will be seen in this output pane. HTTP commands and parameter values are also echoed to the output pane.
Two new tabs appear in the content pane for the servlet: Web View and Web View Source. The running servlets displays in the Web View browser, looking like this:
The Web View tab of the content pane displays the servlet after it has been processed by the JSP engine. The Web View pane will behave differently than the View pane. In the Web View pane, there may be a delay between when the JSP file is edited, and when the change is shown in the Web View pane. To see the most recent changes to an SHTML file, select the reset button, just as you would in any Web browser.
The servlet URL displays in the Web View browser. Now that the Web server, Tomcat, is launched, it displays as a tab below the message pane. To stop the Web server, click the red square directly above the tab. You must stop the Web browser in order to re-run the servlet after you make changes.
Enter a name in the text box, then click the Submit button. The doPost()
method is called, and the response is displayed in the Web View browser, as shown below.
When developing servlets with JBuilder, you have a number of other options for servlet testing and deployment, including
To deploy a servlet onto a Web server, see the documentation for your Web server.
Once you have deployed your application, you can run the client and server on either the same machine or on different machines in the same subnet.
Servlets present an interesting internationalization problem. Since the servlet outputs HTML source to the client, if that HTML contains characters that are not in the character set supported by the server on which the servlet is running, the characters may not be readable on the client's browser. For example, if the server's encoding is set to ISO-8859-1, but the HTML written out by the servlet contains double-byte characters, those characters will not appear correctly on the client's browser, even if the browser is set correctly to view them.
By specifying an encoding in the servlet, the servlet can be deployed on any server without having to know that server's encoding setting. Servlet's can also respond to user input and write out HTML for a selected language.
The following is example of how to specify the encoding setting in a servlet. In the Java source generated by the Servlet wizard, the doPost()
method contains the following line:
PrintWriter out = new PrintWriter(response.getOutputStream());
This line can be replaced with:
OutputStreamWriter writer = new OutputStreamWriter( response.getOutputStream(), "encoding"); PrintWriter out = new PrintWriter(writer);
The second argument to the OutputStreamWriter
constructor is a String representing the desired encoding. This string can be resourced, hard-coded, or set by a variable. A call to System.getProperty("file.encoding")
will return a String representing the system's current encoding setting.
If the OutputStreamWriter
constructor is called with only the first argument, the current encoding setting will be used.
JBuilder provides two new ways to simplify creating data-aware servlets: InternetBeans Express and JSQL/XMLServlet.
InternetBeans Express is a set of components that read HTML forms and generate HTML from dbSwing data models, making it easier to create data-aware servlets and JSPs. InternetBeans Express components generate HTML and are used with Servlets and JSP's to create dynamic content. They feature specific hooks and optimizations when used in conjunction with DataExpress components, but can be used with generic Swing data models. For more information on using InternetBeans Express, including a tutorial, see "Using InternetBeans Express."
JSQL is a command line tool that lets you specify a valid SQL query using XML. XMLServlet takes a SQL query and a description of thedesired report format int he form of XML input, supports a limited XML parser capable of recognizing XML tags, and generates output to an XML-enabled browser accordingly. For more information on using this feature, see "Using XMLServlet."