Servlets are the server-side version of an applet: a small piece of Java code that is loaded by a Web server and used to deal with client requests, much like CGI. Sun Microsystems is aiming to make servlets the new Web server programming paradigm. Servlets are persistent, platform independent, and incorporate all sorts of advanced features including security, easy database access, and much easier integration with Java applets.
Java Servlets are a standard JDK 1.2 extension to JDK 1.1.x. Java Servlet API enables the creation of Java Servlets. Servlets are a means of extending the functionality of servers. For example, servlets can extend a web server's functionality in the same way that CGI scripts do. Servlets, however, are much less resource intensive than CGI scripts. Because servlets are written entirely in Java, again unlike CGI scripts, they are cross-platform as well. JBuilder provides a Servlet Wizard to simplify the creation of servlets. For a tutorial using the Servlet Wizard to create a servlet, see tutorial.
Visit http://www.borland.com/techpubs/jbuilder/ for updates to this topic.
Visit http://www.borland.com/jbuilder/ for a white paper on using servlets in JBuilder.
A Servlet Tutorial is located on the JavaSoft web site at http://www.javasoft.com/products/jdk/1.2/docs/ext/servlet/servlet_tutorial.html.
A Java Servlet Reference Guide with links to sites of interest in the servlet world is located at http://webreview.com/97/10/10/feature/guide.html.
In the Client/Server and Professional editions, JBuilder provides a Servlet Wizard for creating a Java file that extends javax.HTTPServlet. There are several kinds of servlets. The JBuilder Servlet Wizard handles the following kinds:
To develop with servlets,
The Class Path options will automatically show the location of the CLASSES.ZIP file. Click the Browse (...) button, then click Add Zip/JAR to also add the file SERVLET.JAR (located in the \lib\ext\ directory of the JDK 1.2 installation).
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 { //Initialize global variables public void init(ServletConfig config) throws ServletException{ super.init(config); } //Process the HTTP Post request public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintStream out = new PrintStream (response.getOutputStream()); out.println("<html>"); out.println("<head><title>Servlet1</title></head>"); out.println("<body>"); out.println("</body></html>"); } //Get Servlet information public String getServletInfo() { return "untitled1.Servlet1 Information"; } }
The generated file Servlet1.html, that will launch the servlet looks like this:
<HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <TITLE> Servlet1 </TITLE> <BODY> <FORM action=http://yourServerUrl//servelet/untitled1.Servlet1 method=POST> <BR><BR> press Submit to launch servlet Servlet1 <BR><BR><input type=submit><input type=reset></form> </BODY> </HTML>
The servlet runs from inside a Web Server program. Web Servers take HTML pages as their input/ouput. After you have compiled the servlet, you can test and/or debug the servlet by using the Deployment Wizard to bundle up the servlet or by copying the classes to your Web Server to test the servlet. You must deploy the servlet onto your Web Server in order to test it. You can download an evaluation copy of the Java Web Server from http://jserv.javasoft.com/products/webserver/index.html.
Launch the servlet by viewing Servlet1.html file in a Web browser and clicking the Submit button.
This tutorial shows how to create a basic servlet. To develop and deploy servlets, you will need to run a servlet-enabled Web server and use Java Development Kit 1.2, both of which can be downloaded from JavaSoft.
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 Class Path options will automatically show the location of the CLASSES.ZIP file. Click the Browse (...) button, then click Add Zip/JAR to also add the file SERVLET.JAR (located in the \lib\ext\ directory of the JDK 1.2 installation).
Enter firstServlet in the Class field. Click Finish. Files named firstServlet.java and firstServlet.shtml will be added to your project.
If the generated servlet handles doPost() or doGet() methods, an HTML form is generated, otherwise a servlet tag is put in the the HTML and the file is labeled with the SHTML extension. These files need the SHTML extension to be processed correctly by the Web server. In this example, the service() method is generated, so the file is labeled with the SHTML extension.
package firstServlet; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class firstServlet extends HttpServlet { //Initialize global variables public void init(ServletConfig config) throws ServletException { super.init(config); connections = 0; } //Service the request public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get Servlet information //Get a channel to the Web browser, //so we can send output ServletOutputStream out = response.getOutputStream(); response.setContentType("text/html"); //Required for HTTP out.println("<HTML><HEAD><TITLE>Servlets Tutorial</TITLE></HEAD>"); out.print("Hello World - my first Java Servlet Program, "); out.println(request.getParameter("userName")); out.print("<P>You are visitor number "); connections++; out.println(Integer.toString(connections)); //Close the output stream out.close(); } int connections; public String getServletInfo() { return "firstServlet.firstServlet Information"; } }
Once we create the Java code, we have to compile it and place the resulting file on the Web server. Compile the application in JBuilder by right-clicking firstServlet.java in the Navigation pane, then selecting Make.
Files called firstServlet.class and firstServlet.dependency are generated in the directory specified in File|Project Properties Output Root Directory field.
The servlet runs from inside a Web Server program. Web Servers take HTML pages as their input/ouput. After you have compiled the servlet, you can test and/or debug the servlet by using the Deployment Wizard to bundle up the servlet or by copying the classes to your Web Server to test the servlet. You must deploy the servlet onto your Web Server in order to test it.
The first servlet-enabled Web server was JavaSoft's Jeeves, now renamed Java Web Server (JWS). A number of additional server developers have adopted the standard. The latest version of the World Wide Web Consortium's free JigSaw Web Server has servlet support, as does O'Reilly WebSite Pro v2.0. For those running Netscape servers, IIS, Apache and others, JavaSoft distributes the Java Servlet Developers Kit, which allows most standard Web servers to load servlets. Finally, the IBM has released a tool called ServletExpress that makes servlets easier to manage on Web servers lacking native Java support.
To deploy a servlet onto a Web server,
Two items of importance are:
The path in this example assumes that you are running the default Java Web Server installation. (The lack of a trailing s on "servlet" is not a misprint: the directory is called "servlets" and the URL calls for "servlet"). In this example, we are simulating the submission of a FORM to the server with a variable "userName" by passing this variable in the URL.
In this example, a form is presented asking for you to enter your name. When you click the submit button, your submission is sent to the servlet, and the servlet returns its output to your browser.
HttpServlet.init(ServletConfig conf) is executed the first time the servlet loads. Any resources created here (assuming that they are visible to the entire class, like the connections variable) will be accessible to every single servlet invocation. So this is where global variables are created, as well as any resources that do not depend on the individual page request. In this (simplified) example, a variable is initialized to keep track of how many requests have been made for that page.
HttpServlet.service(HttpServletRequest, HttpServletResponse) takes two parameters, the HttpServletRequest and the HttpServletResponse. These are Java objects that exchange information between the servlet and the server, much like the AppletContext object in applets. In this example, HttpServletResponse obtains a ServletOutputStream, which allows the contents to be sent back to the Web browser. In standard CGI, the program would write to standard output.
The three ServletOutputStream methods used are:
The setContentType(String) method is used to tell the browser what type of content it should expect to receive. Normally, this will be "text/html". For reliable operation, this should come before any actual output.
HttpServletRequest includes all the information provided to the servlet by the browser and the Web server (environment information, HTTP variables, form variables and so forth). The HttpServlet.getParameterName(String) method is used to read CGI form variables. In this case, the servlet was passed a variable named "userName" with a value of "John", and the command request.getParameter("userName") will return a String variable containing the text "John".
For other sample servlets, link to http://jserv.javasoft.com:80/products/java-server/documentation/webserver1.0.2/servlets/sample.html, the JavaServer Product Group page with samples for the following applications:
http://server_host_name/system/doc/sample.html
.