Web apps, Tomcat, GGTS

You need to have Java JDK installed prior to installing the software tools described in this document. Refer to the JDK/NetBeans document particular to your system; omit the NetBeans installation for now.

Groovy/Grails Tool Suite (GGTS)

GGSTS is an eclipse-based IDE which comes with the important Java-based Web Tools Package for creating Java server-side web programs as well as the Groovy-Grails packages for creating Groovy-on-Grails web applications. The home site is this:
http://www.springsource.com/developer/sts
The other IDE supported by this site is the Spring Tools Suite (STS) which, by default, omits the Groovy-Grails packages and can be used by itself for creating Java server-side web programs as well as web applications using the Spring MVC web framework.

Our applications for the first part will be Java server-side web programs, but we will allow usage of classes written in Groovy, which is a bit unusual. However, with some small preparation, the GGTS IDE suits our needs very well. Other IDEs such as NetBeans can also be adapted to run Java server-side programs with Groovy classes, but NetBeans does not function quite as well as GGTS.

Download and Install GGTS

Visit the site:
http://www.springsource.com/downloads/sts-ggts
Follow the take me to the download page link. Look for the IDE installation software in the general form:
groovy-grails-tool-suite-3.2.0.RELEASE-e4.2.2-WHATEVER
where WHATEVER relates to your operating system. You can download these from the course site: On Windows or Mac, double-click to start the installation. Unlike other software, the installation is a single directory, springsource, which can be located wherever you like. The downloadable "tarball" file ___.tar.gz works just as well. A good target location is:
/PATH/TO/HOME_DIRECTORY/springsource
Run the application by navigating to
/PATH/TO/springsource/ggts-3.2.0.RELEASE/
and activating the relevant executable.

The version of GGTS is based upon the underlying Eclipse package, which, at version 4.2, is Eclipse Juno. See the Eclipse wikipedia site for more information.

Java Server Side programs

A Java server-side entity is a Java object that can the executed by an HTTP server as the result of the invocation by a browser client. This ability to execute Java is not a modular feature of web servers like Apache and Microsofts IIS, and so we use a specialized web server for that purpose.

In Java-based web applications, the application is referred to as a context and the web server is referred to as a container. A container starts a Java virtual machine (JVM) and handles browser requests by executing them in threads, making the request-handling process very fast.

Apache Tomcat

Although GGTS comes with a built-in container we will prefer the generic tomcat server in a most recent version because we can use this with the NetBeans IDE later. Tomcat only needs needs an existing Java (not necessarily JDK) installation and will presumably the the system version. The Tomcat home page is
http://tomcat.apache.org
The software package you'll need is the following system-independent archive file. You can get it from the home page (for Windows systems, please avoid the Tomcat installer version) or from the course website:
apache-tomcat-7.0.47.zip
The archive file extracts as the directory . You can decide where to put it. Here are some suggestions:
  1. Windows: Extract apache-tomcat-7.0.47.zip into "C:\", getting the installation folder:
    C:\\$this->tomcat\\
    
  2. MAC/Linux: Use this subdirectory in your home directory (you may have to create it):
    ~/Library
    
    Extract the zip file into this directory. From a command line shell you can do:
    $ unzip apache-tomcat-7.0.47.zip -d ~/Library/
    

Add support JAR files

Downlooad and extract the archive ggts-jars.zip. It becomes a directory ggts-jars of JAR files. Move them all into the Tomcat library folder:
/PATH/TO/apache-tomcat-7.0.47/lib/
These are the files within. They provide support for projects in this and related documents.
jstl.jar,                               JSTL Tags
standard.jar
groovy-2.1.3.jar,                       Basic Groovy Programs
asm-4.0.jar
groovy-sql-2.1.3.jar,                   Groovy/SQL/MySQL support
mysql-connector-java-5.1.25-bin.jar
antlr-2.7.7.jar,                        Groovy Script
commons-cli-1.2.jar
groovy-json-2.1.3.jar                   Groovy JSON operations

Tomcat Server instance in GGTS

Start GGTS. Initially you must verify the target "workspace directory."
  1. Right-click in the Project Explorer window. Select New → Other. Open the Server category, select the Server entry within and click Next.
  2. In the Define a New Server window, select Apache → Tomcat v7.0 Server, click Next.
  3. In the Tomcat Server window, click the Browse button to navigate to your Tomcat installation directory. Click Finish.
Back in GGTS, look for the Servers tab at the bottom. You should see the Tomcat 7.0 server at localhost entry listed in there.

Change default ports

By default, Tomcat runs its web service on port 8080 and uses port 8005 and 8009 for related resources. We want to change these to our own "development ports" for use with GGTS. To do so, double-click on the Tomcat entry in the Servers tab to reveal the configuration listing. Shift to the right to find these settings and modify them as follows:
Tomcat admin port  8005
HTTP/1.1           8080
AJP/1.3            8009
⇒  
Tomcat admin port  8105
HTTP/1.1           8180
AJP/1.3            8109
Save the configuration and close this configurator.

Create a sample web application

The GGTS is set to create Groovy-Grails Web Applications which is suggested by the Grails perspective as indicated in the upper right-hand corner of the IDE. This and subsequent documents are about creating Dynamic Web Projects which use the Java EE perspective. Start either from the File menu or by right-clicking on the Project Explorer window.
  1. Create a new Dynamic Web Project. Initially go through the chain:
    New → Project → Web → Dynamic Web Project.
    Set JspHello as the Project Name. Check that the target runtime is Apache Tomcat. Click Finish. Say Yes to the popup about opening the Java EE perspective.
  2. Right-click on the JspHello project and select New → JSP File. Give it the name index.jsp (the .jsp extension is optional, and typing it will not confuse the file name). Click Finish.
  3. Type
    Hello from JSP
    in the document's body and save it. The index.jsp file can be found in the WebContent folder.
  4. Run this web application (with only one file) by clicking the green run button, or by right-clicking on the project and selecting Run As → Run on Server.
  5. A Run On Server popup queries you for the server to use. Double-check that the server is Apache Tomcat. Check the Always use this server when running this project checkbox. Click Finish.
  6. The tomcat server should start and you should see the JSP page displayed in the internal browser.
  7. Double-check the output in an external browser (like Firefox): Enter the URL by hand:

Web application folders

GGTS presents a web application according to the WTP plugin with a somewhat bewildering set of choices:
Deployment Descriptors: JspHello
Java Resources
JavaScript Resources
Web Resources
build
WebContent
Under the hood, there are really only 3 folders:
WebContent   (JSP and web related files)
src          (Java and other source files)
build        (Java class files)
The Java Resources section gives access to the src folder and also shows the library files used as part of the application's build path. The Web Resources section appears to be a mirror of the WebContent folder. The Deployment Descriptors section mostly refers to the contents of the web.xml file (see below) which, in our case, is not present.

Internal or External Browser

I personally prefer an external browser because it makes available the examination of the HTML source and other useful tools like the Firebug console. You can easily go back and forth as you like. Within the Preferences (MAC: GGTS menu, otherwise Window menu), choose General → Web Browser. Observe the choice in the dialog:
 Use internal web browser
 Use external web browser

 Default system web browser
 Firefox                                        (if installed)
To add an external browser, use the New button, setting the Location field to be the location of the executable, perhaps with parameters. If Firefox is present, select it and click Edit to see how the Location is set.

Add more features

Jsp programs provide the ability to generate HTML dynamically in many ways. The most basic is the insertion of Java code within the tags:
<%
  /* Java (not Groovy) code */
%>
We will see that this this inserted Java code, although used for scripting is just one small part of Java-based web applications. In this section we'll take a look at two other very important Java and Groovy programming which can be used.

Add a Java Servlet

  1. Right-click on the JspHello project and select New → Servlet, give the following info and Finish.
    Java package:  servlet
    Class name:    JavaServlet
    
  2. Add the following code into the Servlet's doGet method:
    java.io.PrintWriter out = response.getWriter();
    out.println("Hello from Java Servlet");
    select
  3. In some cases such as adding a new Servlet, we have to restart the server to pick up the changes. Go to the Servers tab. Right-click on the Tomcat Server and select Restart.
  4. Verify the servlet's presence by activating this URL:
Once created, the servlet can be located within the Project Explorer directory structure in two ways: From either of these locations, right-click on the JavaServlet servlet and select Run → Run on Server. After observation, close this window.

Add a Groovy Servlet

GGTS has no direct support for Groovy servlets, but any Java code is effectively Groovy code and so we can add it "by hand" using the Java servlet code as our basis.
  1. From Java Resources → src → servlet, right-click on the servlet package and select:
    New → Other → Groovy → Groovy Class.
    From the dialog enter the name and then click Finish.
    Name: GroovyServlet
    
  2. The initial code is very simplistic. What you need to do is to delete it, copy the code from JavaServlet, paste it in and then modify it, most importantly replacing occurrences of "JavaServlet" by "GroovyServlet". Here are the modifications:
    ...
    @WebServlet("/GroovyServlet")
    public class GroovyServlet extends HttpServlet {
      ... 
      public GroovyServlet() {
        super();
        // TODO Auto-generated constructor stub
      }
      ...
      protected 
         void doGet(HttpServletRequest request, HttpServletResponse response) 
    	        throws ServletException, IOException {
     
        java.io.PrintWriter out = response.writer;  // note the change
        out.println("Hello from GroovyServlet");
      }
      ...
  3. Restart the server to pick up the changes. Go to the Servers tab. Right-click on the Tomcat Server and select Restart.
  4. Verify the servlet's presence by activating this URL: You cannot run the GroovyServlet from the IDE as you did with the JavaServlet. This limitation reflects that fact that JSP-style programming is primarily designed to use Java, not Groovy code.

Add Java and Groovy Beans

  1. Create a new package by selecting New → Package. Give it the name:
    Name: bean
    
  2. In the project, expand Java Resources → src → bean. Right click on the bean package and select:
    New → Class
    From the dialog enter:
    Name: JavaBean
    
    Click Finish. Modify the code to this:
    package bean;
     
    public class JavaBean {
      private String foo;
      public String getFoo() {
        return foo;
      }
      public void setFoo(String foo) {
        this.foo = foo;
      }
    }
  3. In the project, expand Java Resources → src → bean. Right click on the bean package and select:
    New → Other → Groovy → Groovy Class
    From the dialog enter:
    Name: GroovyBean
    
    Click Finish. Modify the code to this:
    package bean
     
    class GroovyBean {
      String bar
    }
  4. Modify index.jsp
    <%/* PUT THESE AT THE TOP */%>
    <jsp:useBean scope="request" id="jb"  class="bean.JavaBean" />
    <jsp:useBean scope="request" id="gb"  class="bean.GroovyBean" />
    ...
    <%/* MODIFY THE BODY */%>
    <body>
    Hello from JSP
    <hr />
    First the set
    <%
    jb.setFoo("Hello");
    gb.setBar("World");
    %>
    then the get:
    <%= jb.getFoo() + " " + gb.getBar()  %>
    </body>
    </html>
  5. There is no need to restart the server. Verify the change to the index page:

Discussion

JSP scripts

JSP scripts appear at first as HTML files with embedded Java code. In fact every JSP script, including the static HTML as well as the embedded Java code, is converted automatically to a Java class and compiled. Indeed, an HTTP request to the JSP script invokes the member function:
public void _jspService(
    HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {
  // converted HTML + Java code
}
select
JSP scripts automatically pre-defines several local variables for use by the scripts:
HttpServletRequest  request
HttpServletResponse response
JspWriter           out          (like PrintWriter in servlets)
HttpSession         session

Compiled code, context reload, server restart

When you run a Java web program, you're actually executing compiled Java .class files at all levels. The simplest level is the Jsp file, which is recompiled and reloaded every time it is modified. If you modify a Java or Grooy source file (e.g., a servlet or a bean), then these files must also get recompiled and reloaded, however, this process is less transparent that the recompilation of JSP files. In particular, you have to look for a specific context reload which is reflected in the Console of the GGTS IDE.

In the case of some modifications, like adding a new Servlet, the server must actually be restarted to recognize its existence. Sometimes you may experience the need to restart the server for other peculiar reasons which are hard to catalog. One of the deficiencies of using NetBeans for these types of applications is that there are more circumstances in which you need to restart the server to pick up changes.

Servlets

The activation of a servlet is initiated by a client-side (browser) request. There are two types of browser requests: GET and POST. GET requests are most standard, usually representing the initial external contact with a web page. POST requests are most common for form processing which involves state changes in some database. In a Java Servlet, a GET or POST request corresponds to an activation of the doGet or doPost function, respectively. Note the usage of the annotation lines in our servlets:
@WebServlet("/JavaServlet")
 
@WebServlet("/GroovyServlet")
This one line provides the information about url-mapping by which the servlet is activated. These annotations are made possible by the class import:
import javax.servlet.annotation.WebServlet;
Using annotations obviates the necessity of providing information about mapping servlets to URLs through the web.xml file common to Java web applications which would be this:
WebContent/WEB-INF/web.xml
For example, the following content in web.xml could be used instead of the annotation:
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
    ...
    <servlet>
        <servlet-name>JavaServlet</servlet-name>
        <servlet-class>servlet.JavaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>JavaServlet</servlet-name>
        <url-pattern>/JavaServlet</url-pattern>
    <servlet-mapping>
    ...
</web-app>
In fact, a more complete match would be this extended annotation:
@WebServlet(
    name = "JavaServlet", 
    urlPatterns = {"/JavaServlet"}
)
Annotations can be used to express every feature used to activate a servlet including parameters, filtering and listeners. A brief explanation can be found in this article:
http://www.javabeat.net/articles/97-new-features-in-servlets-30-1.html

Beans

Beans are Java-based objects (Java or Grooy source) which are characterized primarily by their so-called exposed properties. In particular, a Java Bean exposes a typed property, say Type something, by the existence of one or both of these two member functions:
class MyJavaBean {
  public Type getSomething() { ... }
  public void setSomething(Type something) { ... }
}
There may or may not actually be a data member:
class MyJavaBean {
  private Type something;
  ...
}
In many cases the property is just a formalization of access to the data member:
class MyJavaBean {
  private Type something;
  public Type getSomething() { return something; }
  public void setSomething(Type something) { this.something = something; }
}
What the Groovy Bean does is to make this last situation very simple with this equivalent code:
class MyGroovyBean {
  Type something;
}
select
You can easily override the default behavior by adding one or both of the getter/setter functions. On the other side of the coin, if you use a bean (Java or Groovy) within Groovy code, the usage is simplified:
// Groovy code
MyJavaBean bean = new MyJavaBean()
Type x = bean.something   // equivalently bean.getSomething()
Type y = /* ... */
bean.something = y        // equivalently, bean.setSomething(y)
You can get an inkling by comparing the one line from the JavaServlet
java.io.PrintWriter out = response.getWriter();  
transformed into the equivalent for the GroovyServlet:
java.io.PrintWriter out = response.writer;  

Limitations of Java scripting

The final version of index.jsp indicates a common usage of Java within the scripting tags to access variables of bean classes. Although scripting appears to be a straight-forward method of embedded server-side coding, and commonly used in other server-side languages such as Php, Java-based scripting is avoided in Java web applications. Java with its restricted syntax and data type requirements make it an unsuitable scripting language. For example, the Jsp code containing the following tags makes sense when you consider that the JSP script will ultimately be part of a member function within a Java class:
<% String mystring; %>
...
<% mystring = "Java String"; %>
...
<%= mystring %>
However, it looks out of place in a tag system. Consider also, how one might generate a radio group:
<% for (String str: some_list) { %>
  <input type="radio" value="<%=str%>"> <%= str %>
<% } %>
One problem is that neither of these "markup entities" offers a suitable presentation:
<% for (String str: some_list) { %>
and
<% } %>
Worse yet is incorporating the static HTML into the Java code:
<% for (String str: some_list) { 
  out.println("<input type=\"radio\" value=\"" + str + "\"> " + str);
} %>

Limitations of Servlets

Although Servlets could, in theory, be used for all aspects of server-side applications, they are in fact, a poor choice, primarily because of the awkwardness of generating the "view" portion of web applications. Java has very limited ability to create the HTML-based constructions with its limited String operations. Groovy is better, but the outcome is still not as good as inserting dynamic content within static HTML content in the manner suggested by Jsp scripts. Servlets do, however, have a very useful place in implementing web handler activations which do not, in themselves, generate a view, but simply pass off control to some other view script via redirection or forwarding.

Export/Import

A final step is often to save your project as in some format.

Export/Import as a WAR file

A WAR file is nothing mysterious, it is simply a JAR file (which is a ZIP file). WAR files can be "executed" as a web application (a context) in any Java web server (container). Thus they are primarily meant hold the JSP files and associated .class files, not .java or .groovy source files. GGTS provides the option of saving the source files as well, thus making the WAR files suitablle for import in some other IDE.

It is very easy in eclipe-based IDEs as well as NetBeans to generate WAR files for web applications.

In GGTS, simply right-click on the project and select
Export → WAR file
In the WAR Export dialog, decide whether or not to export the source files
Export source files
Click the Browse button and navigate to a target folder (such as the Desktop). The WAR file name will already be presented. Decide whether it is necessary to overwrite a previous export. Then click Finish.

An exported WAR file can be used to create a "fresh" project, either as the project name itself or as a copy into a new project.

Exporting as a directory

An alternative way to export a project is as a directory. Doing so allows you to import it on top of existing code, thereby overwriting the existing code. Right-click on the project selecting
Export → Export → General → File System
Click Next to reveal the File System dialog. Make the "To directory" be a fresh folder with base name same as your project name. Probably uncheck .classpath and .project. Expand the project folder, probably choosing only the WebContent and src folders. Click Finish.

Import a directory (overwriting existing files)

Select
Import → Import → General → File System
Navigate to the target folder. Select it on the left side, thereby selecting the WebContent and src folders. Click Finish. A popup dialog will go through (if necessary) and query you about all the files which will be overwritten.


© Robert M. Kline