Tomcat/Servlets/JSP with NetBeans
— print (last updated: Oct 31, 2009) print

Select font size:

Server-side web programming

Web applications are client/server applications where the web browser is the client who always initiates the connection. The server is a program running on some computer which is identified by a number called the port to distinguish it from other server programs. Clients access the server program via the pair (server,port) called a socket. The browser client (as well as other client programs) initiates the interaction with a URL request:
protocol://data_source
where the protocol is any number of possiblities, including http, file, https, ftp, etc. The data_source can be any number of things from a regular file on the client machine to a program on some server such as these:
file://file
http://server/dir1/dir2/file
http://server/dir1/program
http://server:port/file       (server running on alternate port)
The protocol normally dictates the port, but we can specify it if the different than the usual one, as in the case of the alternate Tomcat server which we want to use. If the target file is a directory, then a default file or program is chosen as the source.

Server-side web programming means that an HTTP request from a browser causes the web server to run a program which generates HTML (or other data) to sends back to the browser. Server-side programming stands in contrast to client-side programming which is usually equated with JavaScript, but can also be effected by Java Applets, Flash, or any others which provide a browser plugin.

There are two styles that a server-side program can use to generate the HTML code sent to the browser: Both styles have certain advantages and disavantages. One advantage of the embedded code style is that it is easier to adapt static HTML files to dynamic server-side script files. On the other hand, the generative style is more uniform and avoids the sometimes confusing transitions between HTML and the program code.

Apache Tomcat

A Java Servlet or Java Server Page is an object that can the executed by an HTTP server due to the invocation of a browser client. This ability is not automatically part of standard web servers like Apache and Microsoft's IIS via modules, and so we need a specialized web server for that purpose. The Apache open source tomcat web server serves our needs. Its home page is this:
http://tomcat.apache.org
Tomcat runs on port 8080 by default. By doing so it avoids conflict with standard web service on port 80 and permits control by non-root users because ports up to 1024 are restricted to root usage only on UNIX-like systems. The Tomcat web server starts a Java virtual machine (JVM) and handles browser client accesses by executing the requests in threads created by this JVM which makes the entire web service process very fast. The software package you'll need is the Tomcat installation file. You can get it from the Tomcat home page or from here as a hyperlink to the Computer Science website:
apache-tomcat-6.0.20.zip
The tomcat server needs to have pre-existing JRE (Java Runtime Environment) installation. JRE is part of a JDK (Java Development Kit) installation which we will assume has been done (see the JDK/NetBeans document).

    Windows   Linux/Mac    

Windows

Extract apache-tomcat-6.0.20.zip into a dedicated location, which we assume will be "C:\", thus getting the installation directory:
C:\apache-tomcat-6.0.20\

Configure Tomcat Manager

Netbeans controls Tomcat via the manager application which needs to be configured to permit access. The Tomcat manager allows you to dynamically deploy, undeploy, start, stop and restart web applications through a web interface. We can actually have NetBeans configure this for us, but it is useful to know what is going on.

In order use the manager you must define a manager role and set a user/password combination which validates access to this role. Edit the file:
apache-tomcat-6.0.20/conf/tomcat-users.xml
Within the tomcat-users start and end tags (but outside the comments) add the following XML entry:
<user username="admin" password="" roles="manager"/>
For simplicity, we've given access to the manager by using the username admin with empty password. You can make these values anything you'd like.

Configure Tomcat Ports

This section is probably not necessary. Tomcat uses the ports 8005, 8080, 8009, 8443 to run it services. It is possible that some other web-based application running on your system is using one or more of these. For example, on Windows, you may be using both IIS (port 80) as your main web server and Apache (port 8080) for development.

If you are aware of a service conflict, or find that NetBeans cannot start up Tomcat, you may have to change the Tomcat ports. To do so, edit the file
apache-tomcat-6.0.20/conf/server.xml
and search for occurrences of the string "port=". You should find up to three uncommented occurrences:
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000" redirectPort="8443" />
<Server port="8005" shutdown="SHUTDOWN">
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
For our sake, probably the only one that needs to be changed is 8080. Change it is some simple way, like inserting a "1" in place of a "0", for example:
<Connector port="8180" protocol="HTTP/1.1"
           connectionTimeout="20000" redirectPort="8443" />

NetBeans Setup

In NetBeans, install this plugin via the menu Tools Plugins Available Plugins:
Java Web Applications
Now we want to register Tomcat as a NetBeans server. You need to know the Tomcat installation directory used above.
  1. Open the Services window on the left. If necessary bring it up from Windows Services:
  2. Right-click on Servers and select Add Server.
  3. Choose Tomcat 6.0 from the list in the Choose Server popup. Click Next.
  4. In the Add Server Instance window, add this information:
    CataLina Home:  <the Tomcat installation directory>
    UserName:       admin
    Password:       <leave blank>
    
     Create user if it does not exist. (unchecked)
    
    Click Finish.
Then test that NetBeans can control it:
  1. Test startup: Right-click on the Tomcat 6.0 server entry and select Start. If it failed read the failure message closely and try to fix it.
  2. Test shutdown: Right-click on the Tomcat 6.0 server entry and select Stop.
If all goes well you're ready to start creating Java web applications.

Hello World web application

Proceed as follows:
  1. From the Projects window, follow New Project Java Web Web Application.
  2. Set the Project Name to WebHello. Click Next.
  3. Take the default selections:
    Project Name:    WebHello 
    Server:          Tomcat 6.0
    Java EE version: Java EE 5
    Context Path:    /WebHello 
    
    Click Finish (skip the Frameworks dialog).
  4. The root file, index.jsp, is automatically brought up in the editor. The Palette window appears on the right. For the most part, I find the Palette not very helpful, and delete it to get more editor space.
  5. Edit index.jsp, changing the title tags to:
    <title>Web Hello</title>
    
    Change the header tag (in the body) to
    <h2>Web Hello</h2> 
    
  6. Run the project in the usual way you'd run any project. It most likely will use the system default browser and bring up a new browser window or a new tab in an existing browser with the URL:
    http://localhost:8080/WebHello/
    
    displaying what you just created.

    This is the point at which NetBeans accesses the Tomcat Manager. If you see a popup asking for access to the manager, you've made a mistake in the Tomcat server configuration. Go back to the Configure Tomcat Manage section and check your settings.
  7. See the project registered in the Tomcat manager. Open
    http://localhost:8080/
    
    and select the Manager hyperlink. Enter the manager username/password in the authentication popup and look for WebHello in the list.
  8. Run the Clean and Build choice and observe the output. When you build a Web Application, Tomcat creates a ".war" (web archive) file in the dist directory which can be used to upload to other Java-based web servers such as, perhaps, the "production" version of Tomcat running on a different port or different server.

Create a Hello Servlet

Right-click on project:
  1. Select New Servlet (you may have to go through Other initially).
  2. In the Name and Location window, enter this information:
    Class Name:  Hello
    package:     servlet
    
    Click Finish (skip the Configure Servlet Deployment step).
This creates the servlet class servlet.Hello which is brought up in the editor window.
  1. Modify the code in processRequest by simply removing the comment lines
      /* TODO output your page here
    
    and
       */
    
  2. Run this servlet by itself by selecting Hello.java from the project, right-clicking, and selecting Run File. Click OK in the Set Servlet Execution popup.
As before it should bring up a browser window, or a new tab in an existing browser with the following URL and its expected content.
http://localhost:8080/WebHello/Hello

The structure of a Servlet

The activation of a servlet is initiated by a client-side (browser) request. There are two types of requests: GET and POST. GET requests are most standard and always activated by typing any URL into a browser. GET requests are also those in which you see parameters delivered in the URL itself after the "?" character, a portion called the query string. POST requests are less frequent and are normally initiated by HTML forms.

A Java Servlet is an extension of the javax.servlet.http.HttpServlet. A GET or POST request activates one of the two built-in functions: doGet or doPost, respectively. Many server-side programs do not need to differentiate between these two activations and it is often common to merge the behaviors of these activations as is done in Netbeans:

NetBeans Servlet template

package servlet;

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Hello extends HttpServlet {
   
  protected void processRequest(
    HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      /* TODO output your page here
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet Hello</title>");  
      out.println("</head>");
      out.println("<body>");
      out.println(
        "<h1>Servlet Hello at " + request.getContextPath () + "</h1>");
      out.println("</body>");
      out.println("</html>");
      */
    } finally { 
       out.close();
    }
  } 

  protected void doGet(
    HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    processRequest(request, response);
  } 

  protected void doPost(
    HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    processRequest(request, response);
  }

  public String getServletInfo() {
    return "Short description";
  }
}

Further Modifications

Add a link to the servlet

Edit index.jsp and, beneath the header element in the body, add this line :
<a href="Hello">Hello Servlet</a>
Now run the project (not the servlet) and observe that you can activate the servlet through the hyperlink.

Changes in JSP vs. changes in Servlets

Run this little experiment which illusrates about editing changes:
  1. Change the line in index.jsp to:
    <a href="Hello">A Hello Servlet Link</a>
    
    Then simply refresh the browser window (not re-run) to observe that you've picked up the change. Click on the servlet hyperlink again.
  2. Now edit the Hello servlet. Add this line:
    out.println("Test addition");
    
    Just before the line:
    out.println("</body>");
    
    Then Save and refresh the browser and observe that the change is (hopefully) picked up as well.
In past versions of NetBeans, a servlet change would only be picked up when you re-ran the application (creating yet another tab/window). It may be necessary to re-run the application to pick up certain deeper changes.

Create a dynamic JSP hello script

The JSP file index.jsp illustrates primarily static HTML features, but in reality, it is as dynamic as a Servlet. This little example gives us a step towards JSP capabilities: Right-click on project. Select New JSP (you may have to go through Other initially). Enter only the name:
JSP File Name:  hello        (the .jsp extension is automatically added)
Click Finish. Modify hello.jsp to look like this:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<% String title = "JSP Hello"; %>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title><%= title %></title>
  </head>
  <body>
  <h2><%= title %></h2>
  <% out.println("Hello Again"); %>
  </body>
</html>
Then add a hyperlink to this page in index.jsp beneath the hyperlink to the Hello servlet:
<br /><a href="hello.jsp">Hello JSP</a>
When you execute the main program and activate the link You'll see the effects. Here is a description:

Discussion

Tomcat Web configuration file

The key file which controls the web structure of servlets in a Tomcat server is:
Web Pages/WEB-INF/web.xml
The file you're seeing is an XML file which is being displayed through a number of viewer filters. If you click on the XML tab on the far right you'll see the actual file. Here are some of the features to observe:

JSP usage

A JSP script initially appears as an HTML file with embedded Java code. Much of the HTML content of a generated Web page is static and so it is often easier to embed the dynamic aspects of a page within the static content in contrast to servlets which must generate all the HTML code. Going from HTML to Java mode is effected by tag pairs, the most basic being this:
<%  
  /* Java code here */
%>
When a JSP file is functioning more in "Java Mode", it is often convenient to replace out.println statements by the actual HTML code. Towards this end, the Java entry tags are often used in reverse to effect HTML entry from Java, like this:
for (int i=0; ... ) {
  %>
  <!-- HTML code -->
  <%
}
It is common to work mostly in HTML mode make Java control structures "look like tag pairs," e.g.:
<% for (String s: some_list) { %>
  <!-- HTML code -->
<% } %>
<% if (x == 5) { %>
  <!-- HTML code -->
<% else if (x == 6) { %>
  <!-- HTML code -->
<% } %>
One downside of this approach is that this new tag structure, with closing tag "<% } %>" does not "look suitable" for a markup language.

A JSP script does not explicitly specify the doGet and doPost functions of a servlet, but these standard variables which are used in servlets are automatically available to JSP execution:
HttpServletRequest  request
HttpServletResponse response
JspWriter           out          (like PrintWriter in servlets)
HttpSession         session
One can imagine the code within a JSP script as residing inside the usual servlet processRequest function. Indeed, each JSP script, including the static HTML along with the Java code, is converted automatically to a Java class. An HTTP request to the JSP script invokes the function:
public void _jspService(HttpServletRequest request, 
                        HttpServletResponse response)
        throws java.io.IOException, ServletException {
  // converted HTML + Java code
}
Static HTML code is effectively being dumped by out.print statements.

JSP vs. Servlets

One significant advantage of JSP is precisely that you can write HTML code explicitly without having to call Java print operations. In particular, the abundance of double quotes in HTML code makes Servlet HTML generation quite painful.

On the other hand, a Servlet is just a Java class and notions of imports, data members, etc. are the common Java notions, whereas they have more obscure counterparts in JSP. Thus a JSP file is likely to be more obscure and messy with the mingling of Java and HTML, which emphasis on HTML.

In terms of our MVC development, JSP files are considered to be the View generators and special tag languages such as JSTL are employed to make JSP usage more like a markup language. Servlets are considered to be part of the Controller and they are particularly suited for AJAX-type invocations.


© Robert M. Kline