Java Web Application Framework

[article] [edit page] [discussion] [history]

From Humanitarian-FOSS Project Development Site

This tutorial will be cover the Java web application framework, covering several server-side Java programming constructs including: servlets, Java Server Pages (JSPs), Tag libraries, and Java/MySQL connectivity. All of these technologies are used in OpenMRS. This assumes you have downloaded and installed Apache Tomcat.

Contents

File Structure

For this tutorial, you should create a directory named, say mine, in your Tomcat webapps directory and then create the following directory structure:

ram@localhost:~$ cd /usr/local/jakarta-tomcat-{version}/webapps
ram@localhost:webapps$ mkdir mine
ram@localhost:webapps$ mkdir mine/WEB-INF
ram@localhost:webapps$ mkdir mine/WEB-INF/classes
ram@localhost:webapps$ mkdir mine/WEB-INF/lib

Java Servlet

Create a configuration file, named web.xml and store it in your WEB-INF directory. For starters, paste the following XML code, which gives a title and a description for your web app, into the file:


<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	version="2.4">

 <display-name>Java Web Apps Demo</display-name>
  <description>
    Tutorial examples of Java web applications.
  </description>

  <context-param>
      <param-name>webmaster</param-name>
      <param-value>your@email.address</param-value>
      <description>
        The EMAIL address of the administrator to whom questions
        and comments about this application should be addressed.
      </description>
  </context-param>

</web-app>

Next, we provide tags to describe the hello world servlet. Copy the following tags into the web.xml file:

  <servlet>
    <servlet-name>Hi</servlet-name>
    <description>
       A very simple servlet.
    </description>
    <servlet-class>Hi</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Hi</servlet-name>
        <url-pattern>/Hi</url-pattern>
    </servlet-mapping>

These tags establish the following:

  • The <servlet> tag establishes the servlet's name as Hi and specifies that it will be coded in a class called Hi.java.
  • The <servlet-mapping> tag says that this server will handle requests that have the following URL: http://localhost:8080/mine/Hi.

Here's the Java code. Save it in a file named Hi.java in the classes folder of WEB-INF:

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * My test servlet
 * @author Liz Warner
 */

public class Hi extends HttpServlet {

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hola</title>");
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");
        out.println("<h1> Hi </h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

How it works: When you request ../mine/Hi, the Tomcat server will use the information in the XML file to call the doGet() method in Hi.java. The method will output a web page.

Compiling Hi.java

To compile Hi.java change into the classes directory and run something like the following command (or make sure your CLASSPATH environment variable is set properly):

javac -classpath /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/classes.jar:/usr/local\
/apache-tomcat-6.0.16/lib/servlet-api.jar:.  Hi.java

Your final directory contents should look like this:

 META-INF
 WEB-INF/classes/Hi.java
 WEB-INF/classes/Hi.class
 WEB-INF/web.xml

Testing the Servlet

Hopefully you'll see a page that says Hi when you go to: http://localhost:8080/mine/Hi.

Java Server Pages (JSPs)

A Java Server Page is basically an HTML page with segments of Java code contained with <% ... %> tags:

<html><head><title>Very Simple JSP Example</title></head>
<body bgcolor="white">

<h1>Very Basic JSP</h1>

<!-- displaying a single value -->

Current time: <%= new java.util.Date() %>
<br><br>

Reload this page to watch the greeting change.
<br><br>
<b>

<!-- including several lines of Java code in an HTML page -->

<%
	int um = (int)( Math.random() * 5 );
	switch ( um )
	{
		case 0: out.println("Welcome"); break;
		case 1: out.println("Bienvenidos"); break;
		case 2: out.println("Bienvenue"); break;
		case 3: out.println("Bienvenuti"); break;
		case 4: out.println("Willkommen"); break;
		default: out.println("Huh? " + um);
	}
	out.println("<br>");
%>
</b>

</body>
</html>

This example contains two chunks of Java code. The first displays the current date and time and the second displays a random greeting.

Testing the JSP

Copy and paste this code into a file named example.jsp and save it in your webapps/mine directory. You can then request it with the following URL: http://localhost:8080/mine/example.jsp. Try to extend this simple example after reading more about JSPs.

Jakarta Taglibs

The Jakarta project has created libraries of tags that perform very useful and often repeated tasks. Basically a tag, such as the

is associated by the web server with a chunk of useful code--in this case code that displays the current time. Tags can be placed in JSPs. Here's a little program that uses the date/time taglib:

<html><head><title>Simple Taglib Example</title></head>
<body bgcolor="white">

<h1>Simple Taglib Example</h1>

<%@ taglib uri="http://jakarta.apache.org/taglibs/datetime-1.0" 
	prefix="dt" %>

<b> Months of the Year </b>
<br>

<ul>
 <dt:months id="mon">
  <li> <jsp:getProperty name="mon" property="month"/>
 </dt:months>
</ul>

</body>
</html>

Copy and paste this code into a file named tagexample.jsp and save it in your WEB-INF folder. In this example, the <%@ taglib uri=... prefix=dt @%> provides a URI to the taglib used in the program and specifies a prefix to identify references to its tags. In this example the dt:months code segment, a list of month names is retrieved from the taglib and displayed as an unnumbered HTML list.

Downloading the Taglib and Jar File

Before you will be able to run this example, you need to make several changes to your web app:

  • Download the datetime tag library, extract the .tar.gz file and copy the tag library descriptor file, taglibs-datetime.tld, to your WEB-INF directory.
  • Copy the taglibs jar file into WEB-INF/lib. Your WEB-INF directory should now look like this:
 classes/
 lib/
 lib/taglibs-datetime.jar
 taglibs-datetime.tld
 web.xml

  • Paste the following XML directives into your web.xml file.
<taglib>
	<taglib-uri>
		 http://jakarta.apache.org/taglibs/datetime-1.0
	</taglib-uri>
	<taglib-location>
		 /WEB-INF/taglibs-datetime.tld
	</taglib-location>
</taglib>

Testing the Taglib Example

Test the taglib example at the following URL: http://localhost:8080/mine/tagexample.jsp. Try extending the example by using other tags from the nicely documented date-time library: http://jakarta.apache.org/taglibs/doc/datetime-doc/datetime-1.0/.

MySQL and JDBC

Java DataBase Connectivity (JDBC) API provides a programming interface for connecting Java objects and MySQL databases. Let's write a Java servlet that gets its data from an MySQL database. This example assumes you have installed MySQL and you will need to download the mysql-connector-java JDBC package. Download and extract the jar file and move it into your WEB-INF/lib directory.

Use phpMyAdmin to create a database named test that contains a single two-column table named foo with columns named bar (a VARCHAR) and foo_id (an autogenerated INT primary key). Here's an SQL script you can run in MySQL.

Because we are writing a new servlet, you will need to add the following directives to you web.xml file:

    <servlet>
      <servlet-name>DBtest</servlet-name>
      <description>
        Testing Connection to MySQL 
      </description>
      <servlet-class>DBtest</servlet-class>
    </servlet>

    <servlet-mapping>
       <servlet-name>DBtest</servlet-name>
        <url-pattern>/DBtest</url-pattern>
    </servlet-mapping>

As in our first servlet example, the <servlet> tag establishes an association between the servlet and the Java file that implements it, DBtest.java. The second tag says that requests of the form http://localhost:8080/mine/DBtest should be mapped to this servlet by the Tomcat server.

Next copy and paste DBtest.java and save this file in your WEB-INF/classes directory. The following code segment shows how the connection with the MySQL server is made and how a simple query of the animals table is processed :

           try
            {
               //create a new instance of the mysql driver
               Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            }
            catch (Exception Ex)
            {
                out.println("Unable to Load Driver: " + Ex.toString() + "<br>");
            }
                        // get a new connection object 
            conn = DriverManager.getConnection(DBUrl);
            // get a new statement object 
            stmt = conn.createStatement();
            // and execute a simple query 
            ResultSet rs = stmt.executeQuery("SELECT * from animals");

            while (rs.next())
            {
                // iterate through the result set and print 
                // the query results to the page 
                out.println("name = " + rs.getString("name") + "<br>");
            }

You might need to check DBtest.java and change the url, login and password of the database you are using. For example, change:

private String DBUrl = "jdbc:mysql://storage1.cs.trincoll.edu/sahana2_jsptest";

to:

private String DBUrl = "jdbc:mysql://yoururl";

and

conn = DriverManager.getConnection(DBUrl, "sahana_admin", "trysahana");

to:

conn = DriverManager.getConnection(DBUrl, "yourusername", "yourpassword");

Putting It All Together

To put all the previously learned skills together to create a functional web log, do the next step in this tutorial.

References

Personal tools