Java Web Application Framework

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.

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:

 

Java Web Apps Demo Tutorial examples of Java web applications.

 webmaster your@email.address The EMAIL address of the administrator to whom questions and comments about this application should be addressed. 



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

 Hi</servlet-name> <url-pattern>/Hi</url-pattern> </servlet-mapping> These tags establish the following:
 * The 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(" "); out.println(" "); out.println(" Hola "); out.println(" "); out.println("<body bgcolor=\"white\">"); out.println(" Hi "); out.println(" "); out.println(" "); } } 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: Very Simple JSP Example

Very Basic JSP

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

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

<%	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(" "); %> </b>

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 <dt:currentTime/> 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: Simple Taglib Example

Simple Taglib Example

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

 Months of the Year 

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

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: classes/ lib/ lib/taglibs-datetime.jar taglibs-datetime.tld web.xml
 * 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:

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

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: DBtest</servlet-name> Testing Connection to MySQL DBtest</servlet-class>

<servlet-mapping> DBtest</servlet-name> <url-pattern>/DBtest</url-pattern> </servlet-mapping> As in our first servlet example, the   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 + " "); }                       // 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") + " "); }

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.