我无法将表单数据提交到mysql数据库

时间:2015-10-05 02:19:26

标签: java mysql sql-server jsp

由于某些原因,我无法将表单数据提交到我的数据库。我让它在某一点工作但不再是。我包含了几个print语句,以查看是否存在未运行的代码。似乎' if' index.jsp页面中的语句永远不会被执行,因为我甚至不会收到条目失败的警报。我似乎无法找出原因。任何帮助将不胜感激。

DBentry.java

package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

//import com.mysql.jdbc.Connection;
//import com.mysql.jdbc.PreparedStatement;

public class DBentry {

    static DBentry instance = new DBentry();
    Connection dbconn;
    ResultSet results = null;
    java.sql.PreparedStatement sql;
    String dpwd = null;
    StringBuilder sb = new StringBuilder();
    java.sql.Statement stmt = null;


    //change URL to your database server as needed
    String dbPath="jdbc:mysql://localhost:8889/cs485_lab5";

    public static DBentry getInstance() {
        if (instance==null) {
            instance = new DBentry();
        }
        return instance;
    }

    //Establish connection to MySQL server
    public Connection newConnection() {
        System.out.println("establishing connection...");
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            try {           
                dbconn = DriverManager.getConnection(dbPath,"root","root");
                System.out.println("gained the connection");
                return dbconn;
            }
            catch (Exception s){
                System.out.println(s.getStackTrace().toString());}
        }
        catch (Exception err){
            System.out.println(err.getStackTrace().toString());
        }
        return null;
    }

    public ResultSet selectStatement( String query ) {
        try {

            dbconn=instance.newConnection();
            sql= dbconn.prepareStatement(query);
            ResultSet results;
            results=sql.executeQuery();
            System.out.println("query="+query);


            //WARNING!
            //Need to process ResultSet before closing connection
            dbconn.close();
            return results;
        }
        catch (Exception err) {
            System.out.println(err.getMessage());
            return null;
        }
    }

    public boolean DBentry( String query ) {
        try {
            System.out.println("starting DBentry method");
            System.out.println("query="+query);
            instance.newConnection();
            sql= dbconn.prepareStatement(query);
            System.out.println("CONNECTED");
            sql.executeUpdate(query);
            dbconn.close();
            return true;
        }
        catch ( Exception err ) {
            err.getStackTrace();
            return false;
        }
    }

    public boolean entry(String itemNum,String price,String fName,String lName,String shipAdd,String cardType, String ccn ) {
        try {
            System.out.println("entry method executed");
            instance.DBentry("INSERT INTO cs485_lab5.Orders( `Item Number`, `Price`, 'FirstName', 'LastName', 'ShippingAddress', 'CreditCard', 'CCN') " +
                                "VALUES ('"+itemNum+"','"+price+"','"+fName+"','"+lName+"','"+shipAdd+"','"+cardType+"','"+ccn+"');");
            System.out.println("Entry handled");
            return true;
        }
        catch ( Exception err ) {
            err.getStackTrace();
            return false;
        }
    }


    public static void main(String[] args) {    
        //instance.entry("123wdr", "1234.00", "Bill", "Bob", "1234 jon doe street", "Visa", "12345677");
    }
}

ShowParameters.java

package db;

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

public class ShowParameters extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String docType =
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
                "Transitional//EN\">\n";
        String title = "Order Confirmation";

        out.println(docType +
                "<HTML>\n" +
                "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
                "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
                "<TABLE BORDER=1 ALIGN=CENTER>\n" +
                "<TR BGCOLOR=\"#FFAD00\">\n" +
                "<TH>Parameter Name<TH>Parameter Value(s)");

        Enumeration paramNames = request.getParameterNames();
        while(paramNames.hasMoreElements()) {
            String paramName = (String)paramNames.nextElement();
            out.print("<TR><TD>" + paramName + "\n<TD>");
            String[] paramValues =
                    request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() == 0)
                    out.println("<I>No Value</I>");
                else
                    out.println(paramValue);
            } else {
                out.println("<UL>");
                for(int i=0; i<paramValues.length; i++) {
                    out.println("<LI>" + paramValues[i]);
                }
                out.println("</UL>");
            }
        }

        out.println("</TABLE>\n</BODY></HTML>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("STOP1\n");
        doGet(request, response);
    }

}

的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Lab 5</title>
</head>
<body>
<%@ page import="db.*" %>
<body BGCOLOR="#FDF5E6">

<h1 align="center"> Customer Order Form</h1>
<form action="ShowParameters" method="post">
    Item Number: <input type="text" name="itemNum"> <br>
    Price Each: <input value="$" type="text" name="price"> <br>
    <hr>
    First Name: <input type = "text" name = "fname"> <br>
    Last Name: <input type = "text" name = "lname"> <br>
    Shipping Address: <textarea name = "shipadd" style ="resize:none "></textarea> <br>
    Credit Card: <br>
    <input name="creditcard" value ="visa" type="radio">Visa <br>
    <input name="creditcard" value ="mastercard" type="radio">MasterCard <br>
    Credit Card Number: <input name = "ccn" type="text">
    <center><input type="submit" value="Submit Order"></center>
</form>
<%
String itemNum=request.getParameter("itemNum");
String price=request.getParameter("price");
String fName=request.getParameter("fname");
String lName=request.getParameter("lname");
String shipAdd=request.getParameter("shipadd");
String cardType=request.getParameter("creditcard");
String ccn=request.getParameter("ccn");

    System.out.println("Right before the if");
if (itemNum!= null&&!itemNum.trim().equals("")){
    System.out.println("Entering the if");
    DBentry DBentry = new DBentry();
    boolean flag=DBentry.entry(itemNum, price, fName, lName, shipAdd, cardType, ccn);
    if(flag){%><script type="text/javascript">alert("Entry Success");</script><%
    }
    else { %><script type="text/javascript">alert("Entry Failure");</script><%}
}

%>
</body>

</html>

错误

org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 40 in the jsp file: /index.jsp
DBentry cannot be resolved to a type
37:     System.out.println("Right before the if");
38: if (itemNum!= null&&!itemNum.trim().equals("")){
39:     System.out.println("Entering the if");
40:     DBentry DBentry = new DBentry();
41:     boolean flag=DBentry.entry(itemNum, price, fName, lName, shipAdd, cardType, ccn);
42:     if(flag){%><script type="text/javascript">alert("Entry Success");</script><%
43:     }


An error occurred at line: 40 in the jsp file: /index.jsp
DBentry cannot be resolved to a type
37:     System.out.println("Right before the if");
38: if (itemNum!= null&&!itemNum.trim().equals("")){
39:     System.out.println("Entering the if");
40:     DBentry DBentry = new DBentry();
41:     boolean flag=DBentry.entry(itemNum, price, fName, lName, shipAdd, cardType, ccn);
42:     if(flag){%><script type="text/javascript">alert("Entry Success");</script><%
43:     }


Stacktrace:
    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:102)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:198)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:450)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:361)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:585)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:363)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

我在错误之后运行程序,这次它允许我在将DBentry更改为dbentry后填写表单。表格仍然没有提交到数据库。下面是控制台输出。

控制台

Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.24
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Jul 1 2015 20:19:55 UTC
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.24.0
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Mac OS X
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.9.5
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          x86_64
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_60-b27
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         /Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         /Users/pmcphail12/Desktop/apache-tomcat-8.0.24
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=/Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/Users/pmcphail12/Desktop/apache-tomcat-8.0.24
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=/Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/Users/pmcphail12/Desktop/apache-tomcat-8.0.24/endorsed
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Oct 04, 2015 10:31:31 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/pmcphail12/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Oct 04, 2015 10:31:31 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Oct 04, 2015 10:31:31 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Oct 04, 2015 10:31:31 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Oct 04, 2015 10:31:31 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Oct 04, 2015 10:31:31 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1085 ms
Oct 04, 2015 10:31:31 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Oct 04, 2015 10:31:31 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.24
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/Catalina/localhost/Lab1.xml
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.SetContextPropertiesRule begin
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Lab1' did not find a matching property.
Oct 04, 2015 10:31:32 PM org.apache.catalina.core.ContainerBase addChildInternal
SEVERE: ContainerBase.addChild: start: 
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Lab1]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@460e441f]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4845)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4975)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 10 more
Caused by: java.lang.IllegalArgumentException: The main resource set specified [/Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Lab1] is not valid
    at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:723)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:684)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 13 more

Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.HostConfig deployDescriptor
SEVERE: Error deploying configuration descriptor /Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/Catalina/localhost/Lab1.xml
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Lab1]]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:729)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deployment of configuration descriptor /Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/Catalina/localhost/Lab1.xml has finished in 11 ms
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/Catalina/localhost/Lab2.xml
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.SetContextPropertiesRule begin
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Lab2' did not find a matching property.
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deployment of configuration descriptor /Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/Catalina/localhost/Lab2.xml has finished in 23 ms
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/Catalina/localhost/Lab5.xml
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.SetContextPropertiesRule begin
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Lab5' did not find a matching property.
Oct 04, 2015 10:31:32 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deployment of configuration descriptor /Users/pmcphail12/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/Catalina/localhost/Lab5.xml has finished in 288 ms
Oct 04, 2015 10:31:32 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Oct 04, 2015 10:31:32 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 04, 2015 10:31:32 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 745 ms
Right before the if
STOP1

0 个答案:

没有答案