POCMasthead.gif (6305 bytes)

Some Common Servlet Features



This section describes some of the general characteristics of a Java Servlet that are used in the Servlet that is included with this SupportPac.   This section is not intended to be a definitive reference on Java Servlets.   The intent is to provide background so you understand Java Servlets capabilities used by the supplied sample Servlet (plus a few more features).  For a complete list of all Servlet capabilities, read the documentation supplied with WebSphere Application Server.  Some knowledge of Java is assumed in this section. 

In addition to the documentation that comes with WebSphere Application Server, the most current versions of the API references are available on the WebSphere Application Server web site: http://www.software.ibm.com/webservers/appserv/library.html.

The next section discusses the supplied Java Servlet and details what is needed to modify the supplied Java Servlet for use as a Proof-of-Concept for your customer. 

For complete information on Java Servlets see http://www.software.ibm.com/webservers and http://java.sun.com.


This section discusses: 



Java Servlets (High Level)

Servlets are Java programs that use additional packages, and the associated classes and methods, in the JavaSoft Java Servlet Application Programming Interface (API).   Similar to the way applets run on a browser and extend the browser's capabilities, servlets run on a Java-enabled Web server and extend the server's capabilities. 

Servlets extend the capabilities of the server by creating a framework for providing request/response services over the Web. When a web browser sends a request to the server, the server can send the request information to a Servlet and have the Servlet construct the response that the server sends back to the web browser. 

A Servlet can be loaded automatically when the Web server is started, or it can be loaded the first time a web browser requests its services. After loading, a Servlet continues to run, waiting for additional web browser requests. A Servlet can be loaded automatically at server startup, when a web browser first requests the Servlet, or when the Servlet is reloaded.  When the Servlet is loaded, the server creates an instance of the Servlet and calls the Servlet init() method. 

When a web browser request arrives at the web server, the web server creates a Request object and a Response object that are specific to that web browser's request. The server invokes the Servlet service(),  doGet(), or doPost() methods depending on the type of request, or the type of Servlet you write.  There are also doPut() and doDelete() method which will not be discussed in this article. 

The Servlet's destroy() method is invoked when the Servlet is unloaded from the server. 



 
 

Java Servlet Methods 

public void init(ServletConfig config)

The init() method executes only one time when the server loads the Servlet. You can configure the server to load the Servlet when the server starts or when a web browser first accesses the Servlet. The init() is done only one time regardless of how many web browsers access the Servlet. The default init() method is often adequate but, if needed, you can override it with a custom init() method. You would typically use custom init() methods to manage Servlet-wide resources, for example, to write a custom init() to load GIF images only one time or to connect with the CICS Transaction Gateway.  The init() method sets the Servlet's initialization parameters and startup configuration using its ServletConfig object parameter, so any Servlet that overrides the init() method should call super.init() to ensure all necessary setup gets completed. The init() method is guaranteed to complete before the service(), doGet(), or doPost() is called. 

[back to top of Java Servlet Methods]
 
 

public void destroy()

The destroy() method executes only one time when the server stops and unloads the Servlet. Typically, Servlets are stopped as part of the process of bringing the server down. The default destroy() method is often adequate but you can also override it. You would typically use custom destroy() methods to manage Servlet-wide resources. For example, if a Servlet accumulates statistics while it is running, you might want to save the statistics to a file when the Servlet is unloaded, or you might close the connection to your CICS Gateway for Java.  When the server unloads a Servlet, the destroy() method is called after all service(), doGet(), or doPost() method invocations complete or after a specified time interval. If you have spawned threads in your Servlet, you should make sure those threads have ended or completed. 

[back to top of Java Servlet Methods]
 
 

public void service(HttpServletRequest req, HttpServletResponse res)

The service() method is called to receive a single request.  Because the service() method checks whether the request method is HEAD, POST, or GET and calls the appropriate handler method of doPost() or doGet(), it is not necessary to override the service() method. 

[back to top of Java Servlet Methods]

public void doGet(HttpServletRequest req, HttpServletResponse res)

public void doPost(HttpServletRequest req, HttpServletResponse res)

The web server calls the service() method which determines whether the information sent with the request is being provided by GET or POST.  If the form information is being provided by GET, the service() method invokes the doGet() method. If the form information is being provided by POST, the service() method invokes the doPost() method. You do not have to override the service() method, but you must provide code to override doGet() or doPost() to retrieve the information and to prepare the response.  Unlike init() and destroy(), the doGet() or doPost() methods are invoked for each web browser request. 

When a web browser invokes a Servlet directly by its URL, the method is GET. For example, requesting http://myserver/servlet/MyServlet results in a GET. When a web browser invokes a Servlet through an HTML form submission, the form tag specifies if the method is GET or POST. For example, <FORM method=POST action=/Servlet/MyServlet> results in a POST. If the form tag specified method=GET, it would result in a GET. Whether to override doGet, doPost, or both methods depends on how you want web browsers to be able to invoke your Servlet. 

The Servlet can invoke the Request object's methods to get information about the web browser's environment, the server environment, and any information provided by the web browser (for example, form information set by GET or POST). The Servlet invokes the Response object's methods to send the response that it has prepared back to the web browser. To obtain information from the Request object, the Servlet can invoke the getParameterNames(), getParameter(), getParameterValues(), getQueryString(), QueryString(), and parsePostData() methods.

The primary purpose of the Response object is to receive the response from the Servlet that is to be returned to the requesting web browser. Its methods allow you to set the Response header and the Response body. The Response object has the getWriter() method to return a PrintWriter object, and also has the getOutputStream() method to return a ServletOutputStream object. The print() and println() methods of the ServletOutputStream object are used to write the Servlet Response back to the web browser. 

[back to top of Java Servlet Methods]

[top]


State and Persistent Information

There is usually a need to remember state information about a series of web browser requests.  Although this can be done in different ways, a simple way is to use the session tracking framework that is supplied with WebSphere Application Server.  You can obtain an HttpSession object using the HttpServletRequest object's getSession() method. When you first obtain the HttpSession object, the SessionManager creates a unique session ID and typically sends it back to the browser as a cookie. Each subsequent request from this user passes this cookie that contains the session ID. The SessionManager uses this session ID to find the user's existing HttpSession object. If the browsers (or users) you will be working with do not accept cookies, you may want to use an alternate method (see WebSphere Application Server documentation).

The session object can be used to obtain various bits of information to include the referral page, user position, user name, session start time, last access time, and user-defined data that may be stored in the session object. 

The web server can provide its own access control for Web pages and servlets, or you can choose to provide your own logic.  If you use web server authentication,   you can use the getUserName() method of the session object to get the user name (but you cannot get the password).  If you do your own authentication, and want to store the user's name in the session object, you can use the setUserName() method.

The WebSphere Application Server includes classes that make it easier for you to maintain persistent information about the visitors to your Web site and use that information to customize your Web pages. The UserProfile class holds basic information about the user.  The UserProfile class includes data members for a visitor's complete name, postal and e-mail addresses, telephone numbers, and an account or social security number, plus fields to store a language of choice, employment, and user-defined group information. In addition, it has a generic clipboard, message, and shopping cart. This allows you to easily incorporate other objects, of your choice, into these data members and handle them as part of the UserProfile class.  To successfully use the UserProfile class, you must have a JDBC-accessible database (like DB2). It is also possible for you to extend the UserProfile class to create a subclass that better fits your business needs. 

[top]


Adding variable data to your Web pages

Java Server Pages(JSP) provide an easy way to provide dynamic content to your HTML pages. JSP provide you a convenient way to separate your business logic from your HTML content.   You can use JSP to access reusable components, such as servlets, JavaBeans, and Java-based Web applications. JSP also supports embedding inline Java code within Web pages. JSP are extremely flexible and powerful, and can be used many different ways.   Read the WebSphere  documentation for the many ways that JSP can be used for your application.

In the accompanying Servlet, JSP were used to specify variable text in HTML pages based on the values return from CICS.  This facility was used to avoid staticly coding HTML in the Servlet.  This is done by adding data to a JavaBean in your Servlet, then passing the JavaBean to your JSP.  The JSP then accesses the data in the JavaBean and includes the data in the generated HTML that is to be sent back to the browser.  To implement this,
the Servlet: 

  • Instanciates the JavaBean that will contain the data to be passed,
  • Sets values in the JavaBean,
  • Indicates the name of the JavaBean to be passed using the setAttribute() method of the HTTP request object, and
  • Uses the callPage() method of the HTTP response object to indicate the JSP to invoke.
For example:

  POCDataBean dataBean;
  try {
    dataBean = (POCDataBean) Beans.instantiate(this.getClass().getClassLoader(), "POCDataBean");
  } catch (Exception ex) {
    throw new ServletException("Can't create BEAN of class POCDataBean: " + ex);
  }
  dataBean.setTitle("CICS/Servlet Demo Code");       // set property in JavaBean
  dataBean.setServletPath(req.getServletPath());    // set property in JavaBean
  ((com.sun.server.http.HttpServiceRequest) req).setAttribute("dataBean", dataBean);
  ((com.sun.server.http.HttpServiceResponse) res).callPage("/IBMWebAS/jsp/POC/Header.jsp", req);

For purposes of passing data, the JavaBean only needs to contains properties with getter and setter methods for the properties.  For example:

public class POCDataBean {

  private String title;
  private String servletPath;

  public POCDataBean() {
    setTitle("");
    setServletPath("");
  }

  public String getTitle() { return title; }
  public void setTitle(String str) { title = str; }

  public String getServletPath() { return servletPath; }
  public void setServletPath(String str) { servletPath = str; }
}
 

Then, in the JSP, after specifying a /bean tag, you can 

  • use a JSP scriptlet 
  • use a JSP expression 
  • use the <INSERT> tag.
For example in a JSP file, 

<!-- Get the Bean using the BEAN tag -->
<bean name="dataBean" type="POCDataBean" introspect="no" create="no" scope="request"></bean>
<html> 
<head>
<title><%= dataBean.getTitle() %></title>
</head>

<!-- below is a scriptlet (i.e. some Java code) -->
<% if ( !(dataBean.getServletPath()).equals("") )
out.println("<P>The value of the servlet path is " + dataBean.getServletPath()); %>

<!-- below is an expression -->
<P>The value of the servlet path is <%= dataBean.getServletPath() %>

<!-- and an insert tag -->
<P>The value of the servlet path is
<insert bean=dataBean property=servletPath default="No property value" >
</insert></p>
</body>
</html>

Along with the <INSERT> tag, the <REPEAT> and <REPEATGROUP> tags are also very helpful when you have repeating groups of tags or data.

The feature discussed above is only one of many features available with JSP.

[top]


The Site Activity Monitor

The Site Activity Monitor is an applet that lets you view real-time activity within registered applications on your server (like your Servlet). When an application is registered, you can use the Site Activity Monitor to see how many visitors are currently on each page in that application. You can also view any specific information about each visitor that the application might be tracking. 

The supplied sample Servlet does not register itself with the Site Activity Monitor.  You will want to read about this in the supplied WebSphere Application Server documentation.

[top]


Compiling the Servlet

To compile your Servlet: 
  • Establish a path to the Java compiler (if it is not already in place)

  • set PATH=d:\jdk1.1.6\bin;%PATH%
  • Add the following JDK, WebSphere Application Server, and CICS Transaction Gateway classes to your CLASSPATH environment variable (note that the following is one line that has been broken up for readability):

  • set CLASSPATH=.;e:\jdk1.1.6\lib\classes.zip;
    e:\WebSphere\AppServer\lib\ibmwebas.jar;
    e:\WebSphere\AppServer\lib\jst.jar;
    e:\WebSphere\AppServer\lib\jsdk.jar;
    e:\WebSphere\AppServer\lib\x509v1.jar;
    e:\WebSphere\AppServer\lib;
    e:\WebSphere\AppServer\web\classes;
    e:\WebSphere\AppServer\lib\databeans.jar;
    e:\IBM\Connectors\CICS\classes\ctgclient.jar;
    %CLASSPATH%

    (where e:\IBM\Connectors\CICS\classes\ctgclient.jar is the name of the CICS Transaction Gateway classes, and where e:\WebSphere\AppServer is the installation directory of WebSphere Application Server)
    The list of directories is listed in the WebSphere Application Server documentation.

  • Compile the Java Servlet

  • javac filename.java

    Copy the resultant .class file to the WebSphere Application Server directory.

The above commands are for the Windows NT environment.  Use the appropriate commands on the operating system you are using.  Click here to see a .cmd file to set these environment variables in the Windows NT environment.

[top]


Invoking the Servlet

The common ways to invoke a Servlet are: 

Invoke the Servlet directly

You can specify the name or alias of the Servlet directly on your web browser as a URL (e.g. http://webserver/servlet/myservlet (where webserver is the name of the machine running your web server, servlet is the virtual directory where WebSphere Application Server is to find your Servlet (this is the servlets directory of WebSphere Application Server) and myservlet is the name or alias of your Servlet.

[back to "Invoking your Servlet"]

HTML Form: Get Processing (URL-encoding)

You can send additional information to the Servlet by using a URL-encoded query string (this is a common technique).  When using URL-encoded query strings, you append information to the URL. The additional information begins with a question mark, followed by name=value pairs, where name is the name of a parameter and value is the value you want to assign to that parameter. The pairs are separated by an ampersand (&). For example, to pass the first name "John" (on the firstname parameter) and last name "Doe" (on the lastname parameter), you would specify http://webserver/serlet/myservlet?firstname=John&lastname=Doe.  The Java Servlet API provides convenient ways to retrieve URL-encoded information (getQueryString() and parseQueryString()). If you are using the URL-encoded query string to receive information from your browser, you would override the doGet() method in your Servlet to access this data.  There are certain restrictions on the characters you can use, see WebSphere Application Server documentation and/or your web server documentation.

When you invoke a Servlet within a HTML <FORM> tag with GET processing , the web browser does the URL-encoding for you.  The ACTION attribute in the <FORM> tag uses the Servlet alias, rather than the fully qualified path on the server. With the GET method, the user-supplied information is URL-encoded in a query string. 

If the information entered by the user is to be submitted to the Servlet by a GET method, use: 

<FORM METHOD="GET" ACTION="/servlet/myservlet">
(Tags to place text entry areas, buttons, and other prompts go here)
</FORM>
Note that depending on the environment, a long query string might get truncated with GET processing.  This problem does not occur using the POST method.

[back to "Invoking your Servlet"]

HTML Form: Post Processing

With the POST method, the user-supplied information is not appended to the Servlet URL, but is submitted through a separate stream. With POST, the user-supplied information in a long query string is not subject to truncation. 

The getParameterNames(), getParameter(), getParameterValues(), getQueryString(), parseQueryString(), and parsePostData() methods are available for you to extract the query string parameter names and values when using the POST method.

If you want the information entered by the user to be submitted to the Servlet by a POST method, use: 

<FORM METHOD="POST" ACTION="/servlet/myservlet" 
(Tags to place text entry areas, buttons, and other prompts go here.)
</FORM> 
[back to "Invoking your Servlet"]

The SERVLET Tag

When you use the <SERVLET> tag to invoke the Servlet, you do not create an entire HTML page. Instead, the output of the Servlet is only part of an HTML page and it is dynamically embedded within the otherwise static text of the original HTML page. All this takes place on the server (a process called server-side include) and only the resulting HTML page is sent to the user. 

The original HTML page contains the <SERVLET> and </SERVLET> tags. The Servlet is invoked within the <SERVLET> tag, and everything between the two tags, and the tags themselves, are overlaid with what is returned by the Servlet. If the user's browser has the capability to look at the HTML source, the user will not see the <SERVLET> and </SERVLET> tags. The tags and all that is between them will have been overlaid by the Servlet output. 

To use this method of invoking servlets, you must enable the server-side include function on the server. Part of that enablement involves adding a special file type, SHTML (or HTMLS). When the server receives a request for a Web page with the extension SHTML or HTMLS, it searches for the <SERVLET> and </SERVLET> tags and processes the information between the tags. 

The following HTML fragment shows how to use the <SERVLET> tag technique. 

·
<SERVLET NAME="myservlet" CODE="myservlet.class" initparm1="value">
<PARAM NAME="parm1" VALUE="value">
</SERVLET>
·
 
In the above example, initparm1 is the name of an initialization parameter and value is the value of the parameter. You can specify more than one set of name-value pairs. You use the getInitParameterNames() and getInitParameter() methods to find a string array of parameter names and values.  parm1 is set to value after the Servlet is initialized. The parameters set using the <PARAM> tag are available only through methods of a Request object, which means that the server must have invoked the Servlet service() method, passing a request from a user. 

[back to "Invoking your Servlet"]

The <JAVA> Tag

An additional method of invoking Servlets is to embed the coding for the Servlet within <JAVA> and </JAVA> tags that are inline with HTML. The HTML file must have the extension JHTML. When the server receives a request for a JHTML file, the PageCompileServlet processes the file. The PageCompileServlet is part of the WebSphere Application Server package. The Servlet is loaded and initialized when the Webserver starts. For more information about the page compiler, refer to http://jserv.javasoft.com/products/java-server/documentation/toolkit1.1beta/page_comp/intro.html.

When the PageCompileServlet converts the Java code between the <JAVA> and </JAVA> tags into a Java source file, the page compiler compiles the Java source and instantiates the file as a Servlet. The Java Virtual Machine (JVM) runs the Servlet. The page compiler updates the Servlet if the Servlet has been changed on the disk. 

One advantage of embedded Java coding is that the Servlet does not have to be compiled, placed on the server, and defined to the server in advance. This method makes it easier to quickly test Servlet coding. Another advantage is that dynamic and static page content can be placed in the same file. 

The following is a simple example of embedded Java in a JHTML file: 

<html>
<head>
<title>My Page Title</title>
<h1>My Page Heading</h1>
<ul>
<java>
  for (int i=0;i<5;i++)out.println("<li>" +i);
</java>
</ul>
</body>
</html>
[back to "Invoking your Servlet"]
[top]

Making Servlets Threadsafe

Servlets by design have multiple concurrent calls to service(), one for each web browser request. Each call to service(), doGet(), or doPost(), obtains a thread from the Servlet thread pool. When that call returns, the thread is returned to the pool and is available for another service() call instance to use. Also, at any point in the Servlet code, other threads or thread groups can be spawned for processing concurrent tasks. 

You must ensure that servlets are threadsafe. This means that critical sections of code must be protected in some manner. Critical sections are code segments that may be executed concurrently by separate threads and where simultaneous access to the same data would result in incorrect behavior. 

More information on multithreading, see http://www.javasoft.com/docs/books/tutorial/index.html.

[top]



 
 

Last Modified On 01/10/99

[Home]    [Overview]    [Environment]     [Servlets]    [This Servlet]    [Summary]


[ Privacy ][ Legal ][ Search ][ Contact ]