Results 1 to 4 of 4
  1. #1
    play60 is offline Member
    Join Date
    May 2011
    Posts
    4
    Rep Power
    0

    Default Basic Java Bean Help

    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
    <?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>
    web.xml
    <?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>
    MySQLBeanMain.java

    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.
    */
    MySQLBean.java
    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;
    }
    }
    DBResults.java
    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();
    }
    }
    index.html
    <!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.

  2. #2
    play60 is offline Member
    Join Date
    May 2011
    Posts
    4
    Rep Power
    0

    Default

    I started to build my servlet. This is where I am at.

    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;

    public class MySQLServlet extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    MySQLBean = new MySQLBean();
    String docType =
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\"\n";
    String title = "Northwind Results";
    out.print(docType +
    "<HTML>\n" +
    "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
    "<BODY BGCOLOR=\"#FDF5E6\"><CENTER>\n" +
    "<H1>Database Results</H1>\n");
    bean.connectDB = request.getParameter("dbname");
    bean.setUser= request.getParameter("username");
    bean.setPass = request.getParameter("passwd");
    bean.query = request.getParameter("query");
    showTable(connectDB, setUser, setPass, query, out);
    out.println("</CENTER></BODY></HTML>");
    }


    public static void showTable()
    {
    }


    private static void showResults(ResultSet results)
    throws SQLException {
    while(results.next()) {
    System.out.print(results.getString(1) + " ");
    }
    System.out.println();
    }

    private static void printUsage() {
    System.out.println("Usage: PreparedStatements host " +
    "dbName username password " +
    "vendor [print].");
    }
    }
    The errors:

    MySQLServlet.java:12: cannot find symbol
    symbol : variable MySQLBean
    location: class MySQLServlet
    MySQLBean = new MySQLBean();
    ^
    MySQLServlet.java:22: cannot find symbol
    symbol : variable bean
    location: class MySQLServlet
    bean.connectDB = request.getParameter("dbname");
    ^
    MySQLServlet.java:23: cannot find symbol
    symbol : variable bean
    location: class MySQLServlet
    bean.setUser= request.getParameter("username");
    ^
    MySQLServlet.java:24: cannot find symbol
    symbol : variable bean
    location: class MySQLServlet
    bean.setPass = request.getParameter("passwd");
    ^
    MySQLServlet.java:25: cannot find symbol
    symbol : variable bean
    location: class MySQLServlet
    bean.query = request.getParameter("query");
    ^
    MySQLServlet.java:26: cannot find symbol
    symbol : variable connectDB
    location: class MySQLServlet
    showTable(connectDB, setUser, setPass, query, out);
    ^
    MySQLServlet.java:26: cannot find symbol
    symbol : variable setUser
    location: class MySQLServlet
    showTable(connectDB, setUser, setPass, query, out);
    ^
    MySQLServlet.java:26: cannot find symbol
    symbol : variable setPass
    location: class MySQLServlet
    showTable(connectDB, setUser, setPass, query, out);
    ^
    MySQLServlet.java:26: cannot find symbol
    symbol : variable query
    location: class MySQLServlet
    showTable(connectDB, setUser, setPass, query, out);
    ^
    9 Errors


    I'm confused. All my src files are in the same folder. No packages.

    Where do I go from here?

  3. #3
    play60 is offline Member
    Join Date
    May 2011
    Posts
    4
    Rep Power
    0

    Default

    Updated code:

    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;

    public class MySQLServlet extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    MySQLBean databean = new MySQLBean();
    PrintWriter out = response.getWriter();
    databean.connectDB = request.getParameter("dbname");
    databean.setUser= request.getParameter("username");
    databean.setPass = request.getParameter("password");
    databean.query = request.getParameter("query");

    //showTable(connectDB, setUser, setPass, query, out);

    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");
    }
    }
    Errors:

    MySQLServlet.java:13: cannot find symbol
    symbol : variable connectDB
    location: class MySQLBean
    databean.connectDB = request.getParameter("dbname");
    ^
    MySQLServlet.java:14: cannot find symbol
    symbol : variable setUser
    location: class MySQLBean
    databean.setUser= request.getParameter("username");
    ^
    MySQLServlet.java:15: cannot find symbol
    symbol : variable setPass
    location: class MySQLBean
    databean.setPass = request.getParameter("password");
    ^
    MySQLServlet.java:16: cannot find symbol
    symbol : variable query
    location: class MySQLBean
    databean.query = request.getParameter("query");
    ^
    4 errors



    Am I getting closer? Am I on the right path? Do I have to import anything differently?

  4. #4
    play60 is offline Member
    Join Date
    May 2011
    Posts
    4
    Rep Power
    0

    Default

    It now compiles, but it doesn't display results. Page is not found. I believe I need a connection line??

    Updated code:

    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;

    public class MySQLServlet extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    MySQLBean databean = new MySQLBean();
    PrintWriter out = response.getWriter();
    databean.connectDB(request.getParameter("dbname")) ;
    databean.setUser(request.getParameter("username")) ;
    databean.setPass(request.getParameter("password")) ;
    databean.query(request.getParameter("query"));

    //showTable(connectDB, setUser, setPass, query, out);

    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");
    }
    }

Similar Threads

  1. Replies: 1
    Last Post: 03-23-2011, 08:55 AM
  2. any way to communicate one bean to another bean not using session in jsf
    By MayaKannan in forum JavaServer Faces (JSF)
    Replies: 1
    Last Post: 01-14-2011, 02:45 PM
  3. UREGENT-accessing session bean ok but entity bean
    By parimal in forum Enterprise JavaBeans (EJB)
    Replies: 1
    Last Post: 08-28-2008, 02:34 PM
  4. Replies: 0
    Last Post: 03-30-2008, 11:03 AM
  5. Replies: 0
    Last Post: 09-26-2007, 09:36 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •