Tomcat Servlets

Tomcat can be used with either .jsp files or with servlets. This document shows how to use servlets. There are a few main areas where using Tomcat is different than JBoss. JBoss supports CMP, so the database code is created by JBoss. JBoss supports EJB and communication between components using remote and home interfaces. This document will briefly show some of these issues.

Servlets

The servlet URL mapping is in the web.xml file. The web.xml file will go under tomcat/webapps/myapp/WEB-INF.
    <servlet>
	<servlet-name>MyServlet</servlet-name> 
	<servlet-class>mypackage.MyClass</servlet-class> 
    </servlet>
    <servlet-mapping>
	<servlet-name>MyServlet</servlet-name> 
	<url-pattern>/myservleturl</url-pattern> 
    </servlet-mapping>
The following shows some example servlet code. The compiled .class files can be put under tomcat/webapps/myapp/WEB-INF/classes.
public final class MyServlet extends HttpServlet
    {
    // Handle any GET HTTP requests.
    public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
	// Get the parameters from the URL encoding.
	String runparm = request.getParameter("myparm");
	if(runparm == null)
	    {
	    // This will create an HTML page.
	    PrintWriter writer = response.getWriter();
	    writer.println("");
	    writer.println("Hello from my servlet page");
	    writer.println("

Hosted by www.Geocities.ws

"); } else // This will return a serialized string. GetStream(request, response); } }
This code can be put into some HTML to load the servlet and execute the GET HTTP request with no URL encoded parameters.
    <a href="myservleturl">My Servlet Url</a>

If the link above is put into index.jsp, then you can test using: http://localhost:8080/myapp where myapp is the directory under tomcat/webapps.

Applet or Bean Remote Communication

It seems that there are plenty of reasons not to use RMI. It seems to be better to use object serialization over HTTP. The following shows some example servlet HTTP Java object serialization.
    private void GetStream(HttpServletRequest request, HttpServletResponse response)
	throws IOException
	{
	// Get url encoded parameter.
	String myparm = request.getParameter("myparm");
	response.setContentType("application/octet-stream");
	java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(response.getOutputStream());
	// Serialize a string. It inherits from Serializable.
	String myoutstring = "Out: " + myparm;
	oos.writeObject(myoutstring);
	oos.close();
	}
The following shows an example of what can be in a client applet or client bean to deserialize the object from the server. This will invoke the doGet method of the servlet. The compiled .class files can be put under tomcat/webapps/myapp/client/classes.
	// This only works in an applet:
	//	String host = getCodeBase().getHost();
	String host = "localhost";
	int port = 8080;
	java.net.URL url = new java.net.URL(
		"http://" + host + ":" + port + "/myapp/myservleturl" +
		"?myparm=Hello World");
	java.io.ObjectInputStream ois =
		new java.io.ObjectInputStream(url.openStream());
	// Deserialize the string.
	String str = (String)ois.readObject();
	System.output.println(str);

This code can be put into some jsp on the server that will create a page for the client that will load the applet. The support.jar comes with the bean development kit. Note that this can get the parameter from the GET HTTP request, and pass it to the applet.
    <object codebase="client" archive="MyApplet.jar,
	support.jar, MyBean.jar"
	code = "mypackage/client/applets/MyApplet.class"
	width = "600" height = "300" >
	<param name="MyParm" value="<% out.println(request.getParameter("MyParm")); %>"/>
    </object>


Here are some links about RMI.
http://java.sun.com/products/jdk/1.2/docs/guide/rmi/getstart.doc.html
http://developer.java.sun.com/developer/technicalArticles/RMI/rmi

See this link for other remote communication methods. http://archive.devx.com/upload/free/features/javapro/1999/05may99/lo0599/lo0599.asp

MySQL/Java Database Code

The following use this class to access the database.
public class DatabaseConnection
    {
    private String dbURL = "jdbc:mysql://localhost/test";
    private String dbDriver = "com.mysql.jdbc.Driver";		// For Connector/J
    private Connection dbConnection;

    public DatabaseConnection()
	throws java.sql.SQLException
	{
	try
	    {
	    Class.forName(dbDriver);
	    DriverManager.registerDriver(DriverManager.getDriver(dbDriver));
	    }
	catch(ClassNotFoundException ce)
	    { System.out.println("dbConnection c "+ce); }
	catch(java.sql.SQLException se)
	    { System.out.println("dbConnection s "+se); }
	// Try the connection even if something might have failed above.
	try
	    { dbConnection = DriverManager.getConnection(dbURL); }
	catch(java.sql.SQLException se2)
	    { System.out.println("dbConnection s "+se2); throw se2; }
	}
    public void close()
    	throws java.sql.SQLException
    	{ dbConnection.close(); }
    public ResultSet query(String query)
    	throws java.sql.SQLException
    	{
	Statement s = dbConnection.createStatement();
	ResultSet rs = s.executeQuery(query);
	return rs;
        }
    public void update(String query)
	throws java.sql.SQLException
	{
	Statement s = dbConnection.createStatement(
		java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
		java.sql.ResultSet.CONCUR_UPDATABLE);
	s.executeUpdate(query);
	s.close();
	}
    public void create(String crtext)
	throws java.sql.SQLException
	{
	java.sql.Statement s = dbConnection.createStatement(
		java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
		java.sql.ResultSet.CONCUR_UPDATABLE);
	s.execute(crtext);
	s.close();
	}
    }
The following shows the SQL to create a table.
	DatabaseConnection db = new DatabaseConnection()
	db.create("CREATE Table MyTable" +
		"(MyField1 INTEGER primary key, MyField2 INTEGER," +
		"MyField3 VARCHAR(32))");
The following shows the SQL to insert some rows.
    DatabaseConnection db = new DatabaseConnection()
    for(int i=0; i<3; i++)
	{
	String fld3str = "\"" + i + "\"";	// VARCHAR fields must be quoted.
	db.update("insert into Sequence (MyField1, MyField2, MyField3)" +
		"VALUES(" + i + "," + i*10 + "," + fld3str + ")");
	}
The following shows some SQL to get the data.
    java.util.Collection col = new java.util.ArrayList();
    DatabaseConnection db = new DatabaseConnection();
    java.sql.ResultSet rs = db.query(
	"SELECT MyField1 FROM MyTable ORDER BY MyField1;");
    while(rs.next())
	col.add("" + rs.getInt(1));	// Just get MyField1.

Building

Tomcat must be restarted in order to load the new Java classes. It is best to build the classes into a build directory, and then distribute them to the Tomcat deployment (webapps) directory. 1