I am working on my first Java Bean. I was given partial code from my professor and went from there.
Here is all of my code:
build.xml
web.xmlQuote:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Ant build file used for building Java webapp programs with servlet code. Just edit
the name property to reflect the filename of the Webapp you wish to deploy to Tomcat.
-->
<project basedir="." default="deploy" name="MySQLBean">
<!-- Setup the environment variables -->
<property name="name" value="${ant.project.name}"/>
<property name="classes" value="${basedir}/classes"/>
<property name="dep_cache" value="${basedir}/cache"/>
<!-- Choose ONE of the following Tomcat services -->
<!--
<property name="tomcat" value="D:/xampp-1.7.4/tomcat"/>
-->
<property name="tomcat" value="C:/Program Files/Apache Software Foundation/Tomcat 7.0"/>
<property name="webapps" value="${tomcat}/webapps"/>
<!-- Stop Tomcat; Clean build and distribution directories -->
<target name="clean" description="stops tomcat; removes the build and deployment directories">
<!-- Option ONE: Shuts down the Tomcat server using the XAMPP supplied batch file: -->
<!--
<exec executable="cmd">
<arg value="/c"/>
<arg value="${tomcat}/bin/shutdown.bat"/>
</exec>
-->
<delete dir="${classes}"/>
<delete dir="${dep_cache}"/>
<delete dir="META-INF"/>
<delete file="${name}.war"/>
<delete dir="${webapps}/${name}"/>
<delete file="${webapps}/${name}.war"/>
</target>
<!-- Init directories -->
<target name="init" description="creates the build directory">
<mkdir dir="${classes}"/>
</target>
<!-- Build the class files -->
<target name="build" depends="init" description="builds everything in /src into /classes">
<property name="src" value="${basedir}/src"/>
<!-- Update dependency cache -->
<depend srcdir="${src}" destdir="${classes}" cache="${dep_cache}" closure="no" />
<path id="jee-classdefs" >
<pathelement location="${tomcat}/lib/servlet-api.jar"/>
</path>
<javac destdir="${classes}" srcdir="${src}" classpathref="jee-classdefs"
deprecation="on" debug="true" debuglevel="lines, vars, and source"
includeAntRuntime="no"/>
</target>
<!-- Build the .war file -->
<target name="war" depends="build" description="creates the web archive file">
<property name="html" value="${basedir}/html"/>
<war warfile="${name}.war" webxml="${basedir}/web.xml">
<classes dir="${classes}"/>
<fileset dir="${html}"/>
</war>
</target>
<!-- Deploy the .war file -->
<target name="deploy" depends="war" description="moves the .war file to Tomcat's deployment dir">
<delete dir="${webapps}/${name}"/>
<copy file="${name}.war" todir="${webapps}"/>
<copy file="${basedir}/mysql-connector-java-5.1.7-bin.jar" todir="${tomcat}/lib"/>
<!-- The run target below can replace the following echos: -->
<echo message="To run, start Tomcat and browse:"/>
<echo message=" 'http://localhost:8080/${name}'"/>
</target>
<!-- Run the client's browser on the deployed webapp -->
<target name="run" depends="deploy" description="runs the client's browser on the deployed webapp">
<property name="ff" location="C:/Program Files (x86)/Mozilla Firefox/firefox.exe"/>
<property name="ie" location="C:/Program Files/Internet Explorer/iexplore.exe"/>
<property name="url" value="http://localhost:8080/${name}"/>
<!-- Execute Tomcat and spawn an IE or FF browser on the webapp's URL -->
<!-- Batch file execution of Tomcat, use ONE of the following: -->
<!--
<exec executable="cmd">
<arg value="/c"/>
<arg value="${tomcat}/bin/startup.bat"/>
</exec>
-->
<!-- Batch file used with tomcat.apache.org service for Tomcat 7 -->
<exec executable="${tomcat}/bin/tomcat7.exe"/>
<!-- EDIT THE FOLLOWING LINE TO SELECT YOUR CLIENT'S BROWSER -->
<exec executable="${ff}" spawn="true">
<arg value="${url}"/>
</exec>
</target>
</project>
MySQLBeanMain.javaQuote:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>DBwebapp</servlet-name>
<servlet-class>corservlets.MySQLBean</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DBwebapp</servlet-name>
<url-pattern>/processform/</url-pattern>
</servlet-mapping>
</web-app>
MySQLBean.javaQuote:
package coreservlets;
import java.io.*;
public class MySQLBeanMain
{
public static void main(String[] args)
{ // shows the use of the bean:
MySQLBean databean = new MySQLBean();
databean.setUser("root");
databean.setPass("");
databean.connectDB("books");
databean.query("SELECT * FROM titles;");
// check the results of the query,
if (databean.results != null)
{ // and process the result set:
DBResults myresults = databean.processResults();
generateHTMLFile(myresults, "dbtable.html");
}
else System.out.println("No Results!");
}
public static void generateHTMLFile(DBResults results, String filename)
{ PrintWriter out = null; // local variable that holds the output stream
try
{ out = new PrintWriter(new FileOutputStream(filename));
out.println("<HTML>\n" + results.toHTMLTable("Orange") + "\n</HTML>");
}
catch (Exception e)
{ System.err.println("*** " + e.getMessage() + " ***");
}
finally
{ out.close();
}
System.out.println("Check file: " + filename + " for results");
}
}
/* Other queries to do include:
1) SELECT * FROM authors;
2) SELECT FirstName, LastName, Title
FROM authors a, titles t, authorisbn ai
WHERE ai.AuthorID = a.AuthorID and ai.isbn = t.isbn;
The long query above must all be on one line to work.
*/
DBResults.javaQuote:
package coreservlets;
import java.sql.*;
public class MySQLBean
{ // input instance vars:
protected String host; // the MySQL sever (usually localhost)
protected String user; // the MySQL user name (usually root)
protected String password; // the user's password (usually "")
protected String database; // the MySQL DB name to access.
// generated instance vars:
protected int error; // the MySQL error code (0 for success)
protected Connection con; // the connection to the database
public ResultSet results; // a public result set for processing later
public MySQLBean()
{ host = "localhost";
user = "root";
password = "";
database = "test";
}
public MySQLBean(String h, String u, String p)
{ host = h;
user = u;
password = p;
database = "";
}
public void setHost(String s) { host = s; }
public void setUser(String s) { user = s; }
public void setPass(String s) { password = s; }
public String getHost() { return host; }
public String getUser() { return user; }
/* The following Loader class was taken from:
* JavaCoding.net | Java Coding
* Warning: it terminates the program if the driver fails to load properly.
* The newInstance() call is a work around for some broken Java implementations.
* Feel free to remove it if it's not needed on your JVM.
*/
protected void loadDriver()
{ try
{ // Class.forName("org.gjt.mm.mysql.Driver"); // old way
Class.forName("com.mysql.jdbc.Driver").newInstance (); // new way
System.out.println("MySQL Driver Successfully Loaded");
}
catch (ClassNotFoundException e)
{ System.err.println("*** MySQL JDBC Driver not found ***");
e.printStackTrace();
System.exit(-1);
}
catch (Exception e)
{ System.err.println("*** Exception (while attempting to load driver) ***");
e.printStackTrace();
System.exit(-1);
}
}
public boolean connectDB(String dbname)
{ loadDriver();
if ((dbname != null) && (dbname != "")) database = dbname;
// String url = "jdbc:mysql://" + host + "/" + database + "?user=" + user + "&password=" + password;
String url = "jdbc:mysql://" + host + "/" + database;
try
{ // use one connection form or the other both above and below!
// con = DriverManager.getConnection(url);
con = DriverManager.getConnection(url, user, password);
System.out.println("Connection to " + host + ":" + database + " is established");
error = 0;
return true;
}
catch (java.sql.SQLException e)
{ System.err.println("*** Connection couldn't be established to " + host + ":" + database + " ***");
error = e.getErrorCode();
return false;
}
}
public boolean query(String q) // use this for SELECT stmts.
{ try
{ Statement s = con.createStatement();
results = s.executeQuery(q);
return true;
}
catch (java.sql.SQLException e)
{ error = e.getErrorCode();
return false;
}
}
public boolean update(String q) // use this for INSERT/UPDATE/DELETE stmts.
{ try
{ Statement s = con.createStatement();
s.executeUpdate(q);
return true;
}
catch (java.sql.SQLException e)
{ error = e.getErrorCode();
return false;
}
}
public DBResults processResults()
{ // use helper class DBResults to generate an HTML table
DBResults dbresults = null;
try
{ ResultSetMetaData resultsMetaData = results.getMetaData();
int columnCount = resultsMetaData.getColumnCount();
String[] columnNames = new String[columnCount];
// Column index starts at 1 (a la SQL) not 0 (a la Java).
for (int i=1; i <= columnCount; ++i)
columnNames[i-1] = resultsMetaData.getColumnName(i).trim();
DatabaseMetaData dbMetaData = con.getMetaData();
String productName = dbMetaData.getDatabaseProductName();
String productVersion = dbMetaData.getDatabaseProductVersion();
dbresults = new DBResults(productName, productVersion, columnCount, columnNames);
// populate the DBResults internal collection of rows from DB
while (results.next())
{ // extract row data
String[] row = new String[columnCount];
// Again, ResultSet index starts at 1, not 0.
for(int i=1; i <= columnCount; ++i)
{ String entry = results.getString(i);
if (entry != null) entry = entry.trim();
row[i-1] = entry;
}
dbresults.addRow(row);
}
}
catch (SQLException e)
{ System.err.println("*** SQL error: " + e.getMessage());
}
finally
{ try
{ results.close();
con.close();
}
catch (Exception e)
{ System.err.println("*** Error closing con: " + e.getMessage());
}
}
return dbresults;
}
public String reportError()
{ String err; // the English error string
switch (error)
{ // 1000+ error codes are mysql generated and not all
// error codes are listed here, which is why there'll be
// alot of default calls. To add a new error code, use:
//
// case XXXX:
// err = "some error string";
// break;
case 1045: err = "Access denied for user: " + user;
break;
case 1049: err = database + " is not reconized on " + host;
break;
case 1146: err = "Table does not exist";
break;
default: err = "Unknown error code " + error;
break;
}
return err;
}
}
index.htmlQuote:
package coreservlets;
//import java.sql.*;
import java.util.*;
/** Class to store completed results of a JDBC Query.
* Differs from a ResultSet in several ways:
* <UL>
* <LI>ResultSet doesn't necessarily have all the data;
* reconnection to database occurs as you ask for
* later rows.
* <LI>This class stores results as strings, in arrays.
* <LI>This class includes DatabaseMetaData (database product
* name and version) and ResultSetMetaData
* (the column names).
* <LI>This class has a toHTMLTable method that turns
* the results into a long string corresponding to
* an HTML table.
* </UL>
*/
public class DBResults
{ private String productName;
private String productVersion;
private int columnCount;
private String[] columnNames;
private ArrayList<String[]> queryResults;
public DBResults(String productName,
String productVersion,
int columnCount,
String[] columnNames)
{ this.productName = productName;
this.productVersion = productVersion;
this.columnCount = columnCount;
this.columnNames = columnNames;
queryResults = new ArrayList<String[]>();
}
public String getProductName()
{ return(productName);
}
public String getProductVersion()
{ return(productVersion);
}
public int getColumnCount()
{ return(columnCount);
}
public String[] getColumnNames()
{ return(columnNames);
}
public int getRowCount()
{ return(queryResults.size());
}
public String[] getRow(int index)
{ return (String[]) queryResults.get(index);
}
public void addRow(String[] row)
{ queryResults.add(row);
}
/** Output the results as an HTML table, with
* the column names as headings and the rest of
* the results filling regular data cells.
*/
public String toHTMLTable(String headingColor)
{ StringBuffer buffer = new StringBuffer(" <TABLE BORDER=1>\n");
// process table headings
if (headingColor != null)
buffer.append(" <TR BGCOLOR=\"" + headingColor + "\">\n ");
else
buffer.append(" <TR>\n ");
for (int col=0; col < getColumnCount(); ++col)
buffer.append("<TH>" + columnNames[col] + "</th>");
buffer.append("</tr>");
// process table body
for (int row=0; row < getRowCount(); ++row)
{ buffer.append("\n <TR>\n ");
String[] rowData = getRow(row);
for (int col=0; col < getColumnCount(); ++col)
buffer.append("<TD>" + rowData[col] + "</td>");
buffer.append("</tr>");
}
buffer.append("\n </TABLE>");
return buffer.toString();
}
}
Quote:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<p>HTML Form</p>
<FORM ACTION="http://localhost:8080/MySQLBean/processform">
Database: <INPUT TYPE="TEXT" NAME="dbname"><BR>
User: <INPUT TYPE="TEXT" NAME="mysqluser"><BR>
Password: <INPUT TYPE="TEXT" NAME="passwd"><BR>
DB Query: <INPUT TYPE="TEXT" NAME="query"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
</body>
</html>
As of right now it will deploy, but it doesn't process the form. Any help would be appreciated. Thank you.
