servlet和HTML表单之间的连接不起作用

时间:2019-08-29 21:19:17

标签: java html servlets

我在HTML页面和Java中的servlet之间的连接中遇到问题。几天前我已经遇到了这个问题,但这是我在项目管理中的错误。 现在,在我看来,我已正确地完成了所有工作,但我无法处理。 特别是,我正在创建一个HTML页面,其中包含一个带有调用servlet动作的表单。当我创建一个新的Dynamic Web项目时,我的HTML页面位于Eclipse自动创建的“ Web content”目录上。

我的WebServlet批注是“ @WebServlet(/ UploadBook)”,并且表单标签上的操作是“ action = UploadBook”。

当我单击提交按钮时,这是我收到的消息:

未找到 在此服务器上找不到请求的URL / coltraneShop / Administrator / adminColtraneShop / WebContent / UploadBook。

我在MacOS上使用Firefox,并且apache webServer已启动。此外,我在Eclipse的服务器tomcat 9上添加了Dynamic Web项目,并毫无问题地启动了它。

这是我的servlet Java代码:

package insertion;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UploadBook")
public class UploadBook extends HttpServlet {
    private static final long serialVersionUID = 1L;


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out= response.getWriter();
    Long productCode= (long) 0;

    //Fetch data from HTML form method POST
    String title= request.getParameter("Title");
    String quantity= request.getParameter("Quantity");
    String yearOfPublication= request.getParameter("yearOfPublication");

    String genre= request.getParameter("Genre");
    String numPages= request.getParameter("numPages");
    String ISBN= request.getParameter("ISBN");
    String publisher= request.getParameter("publisher");

    String writerName1= request.getParameter("writerName1");
    String writerSurname1= request.getParameter("writerSurname1");
    String writerDateOfBirth1= request.getParameter("writerDateOfBirth1");
    String writerGender1= request.getParameter("writerGender1");

    Connection connection= null;

    //Connect to DB
    try {
        connection= connectDB();
    } 
    catch (ClassNotFoundException | SQLException ConnectionException) {
        System.out.println("Error in connection!");
        out.print("Connection to DB is not avaiable. " + ConnectionException.getMessage());
    }

    //Send query to DB
    try {   
        //Preparing statement and query to DB
        PreparedStatement statementProduct = connection.prepareStatement("INSERT INTO coltraneShop.Product (Category, `Title`, Quantity, `Year of publication`)"
                + "VALUES ('Book', ?, ?, ?);", Statement.RETURN_GENERATED_KEYS);

        //Passing parameters
        statementProduct.setString(1, title);
        statementProduct.setInt(2, Integer.parseInt(quantity));
        statementProduct.setInt(3, Integer.parseInt(yearOfPublication));

        int affectedRows= statementProduct.executeUpdate();
        if(affectedRows == 0)
            throw new SQLException("Creating product failed, no rows affected.");

        //Return ID of product insert in DB
        ResultSet resultSet = statementProduct.getGeneratedKeys();
        if(resultSet.next())
            productCode= resultSet.getLong(1);  

        statementProduct.close();
        out.print("<p>Added a product</p><br>");

        PreparedStatement statementBook = connection.prepareStatement("INSERT INTO coltraneShop.Book VALUES (?, ?, ?, ?, ?);");
        statementBook.setString(1, genre);
        statementBook.setInt(2, Integer.parseInt(numPages));
        statementBook.setLong(3, Long.parseLong(ISBN));
        statementBook.setString(4, publisher);
        statementBook.setLong(5, productCode);

        int affectedRowsBook= statementBook.executeUpdate();
        if(affectedRowsBook == 0)
            throw new SQLException("Creating book failed, no rows affected.");

        statementBook.close();
        out.print("<p>Added a book</p><br>");


        PreparedStatement statementWriter1 = connection.prepareStatement("INSERT INTO coltraneShop. VALUES (?, ?, ?, ?);");
        statementWriter1.setString(1, writerName1);
        statementWriter1.setString(2, writerSurname1);
        statementWriter1.setString(3, writerDateOfBirth1);
        statementWriter1.setString(4, writerGender1);

        int affectedRowswriter1= statementWriter1.executeUpdate();
        if(affectedRowswriter1 == 0)
            throw new SQLException("Creating writer failed, no rows affected.");

        statementWriter1.close();
        out.print("<p>Added a writer</p><br>");

        int elementInRequest= request.getContentLength();
        if(elementInRequest > 10) {

            int numAdditionalWriter= (elementInRequest - 10) / 4;

            for(int i=0; i<(numAdditionalWriter); i++) {
                PreparedStatement statementAdditionalWriter= connection.prepareStatement("INSERT INTO coltraneShop. VALUES (?, ?, ?, ?);");
                statementAdditionalWriter.setString(1, ("writerName" + (i+2)));
                statementAdditionalWriter.setString(2, ("writerSurname" + (i+2)));
                statementAdditionalWriter.setString(3, "writerDateOfBirth" + (i+2));
                statementAdditionalWriter.setString(4, "writerGender" + (i+2));

                int affectedRowsAdditionalWriter= statementAdditionalWriter.executeUpdate();
                if(affectedRowsAdditionalWriter == 0)
                    throw new SQLException("Creating addtional writer failed, no rows affected.");

                statementAdditionalWriter.close();
                out.print("<p>Added a writer</p><br>");
            }
        }

    } 
    catch (SQLException exceptionInQuery) {
        System.out.println("Error in the query");
        out.print("Error in statement or process of sending queries to the database. " + exceptionInQuery.getMessage());
    }

    try {
        connection.close();
    } 
    catch (SQLException closeConnectionException) {
        System.out.println("Problem in closing connection");
        out.print("Problem in closing connection. " + closeConnectionException.getMessage());
    }

    out.close();
}

private Connection connectDB() throws ClassNotFoundException, SQLException {
        Connection connection= null;
        Class.forName("com.mysql.cj.jdbc.Driver");
        connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/coltraneShop?useTimezone=true&serverTimezone=UTC", "root", "");
        return connection;
}

}

这是我的HTML表单代码:

<head>
    <title>Insert book in the database</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="UTF-8">
    <!--Bootstrap CSS-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <script src="administrator.js"></script>
</head>

<body>
    <form action="UploadBook" method="POST">
        <div class="container">

            <div class="form-group">
                <label> <strong>Title:</strong> </label>
                <input type="text" name="Title" class="form-control" placeholder="Title of book" maxlength="50" required>
            </div>

            <div class="form-group">
                <label> <strong>Quantity:</strong> </label>
                <input type="text" class="form-control" name="Quantity" placeholder="Max quantity in stock can be 999" maxlength="3" pattern="[0-9]{1,3}" onkeydown="return isNumberKey(event)" required></input>
            </div>

            <div class="form-group">
                <label> <strong>Year of publication:</strong> </label>
                <input type="text" class="form-control" name="yearOfPublication" placeholder="Year of publication" maxlength="4" pattern="[0-9]{1,4}" onkeydown="return isNumberKey(event)" required></input>
            </div>

            <div class="form-group">
                <label> <strong>Genre:</strong> </label>
                <select class="form-control" name= "Genre" required>
                    <option value="History" >History</option>
                    <option value="Fantasy">Fantasy</option>
                    <option value="Child">Child</option>
                    <option value="Art">Art</option>
                    <option value="Music">Music</option>
                    <option value="Thriller">Thriller</option>
                    <option value="Travel">Travel</option>
                    <option value="Biography">Biography</option>
                    <option value="Poetry">Poetry</option>
                    <option value="Romance">Romance</option>
                    <option value="Science">Science</option>
                </select>
            </div>

            <div class="form-group">
                <label> <strong>Number of pages:</strong> </label>
                <input type="text" class="form-control" name="numPages" placeholder="Max length: 99.999 pages" maxlength="5" pattern="[0-9]{1,5}" onkeydown="return isNumberKey(event)" required></input>
            </div>

            <div class="form-group">
                <label> <strong>ISBN:</strong> </label>
                <input type="text" class="form-control" name="ISBN" placeholder="13-digit code" maxlength="13" pattern="[0-9]{1,13}" onkeydown="return isNumberKey(event)" required></input>
            </div>

            <div class="form-group">
                <label> <strong>Publisher:</strong> </label>
                <input type="text" class="form-control" name="publisher" placeholder="The name of the publishing house" maxlength="30" required></input>
            </div>

            <div class="form-group">
                <label> <strong>Writer's name:</strong> </label>
                <input type="text" class="form-control" name="writerName1" placeholder="The name of the Writer" maxlength="20" required></input>
            </div>

            <div class="form-group">
                <label> <strong>Writer's surname:</strong> </label>
                <input type="text" class="form-control" name="writerSurname1" placeholder="The surname of the Writer" maxlength="20" pattern="[A-z]{1,20}" required></input>
            </div>

            <div class="form-group">
                <label> <strong>Writer's date of birth:</strong> </label>
                <input type="date" class="form-control" name="writerDateOfBirth1"></input>
            </div>

            <div class="form-group">
                <label> <strong>Writer's gender:</strong> </label>
                <input type="text" class="form-control" name="writerGender1" placeholder="Gender of writer: can be 'M' or 'F' or 'N(on defined)'" maxlength="1" pattern="^(M|F|N)" ></input>
            </div>

            <div class="form-group" id="containerWriters">
                <button type="button" class="btn btn-outline-success" id="addWriterButton" onclick="addWriter()"> Add Writer </button>
                <button type="button" class="btn btn-outline-danger" id="removeWriterButton" onclick="removeWriter()"> Remove Writer </button>
            </div>

            <!--Submit all data -->
            <input type="submit" class="btn btn-primary btn-lg btn-block" value="Insert" id="submit"></input>

        </div> <!--Container div-->
    </form>

    <!-- Bootstrap jQuery, Ajax and JavaScript-->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

似乎您是直接从文件系统加载文件,并试图调用此servlet。这是不正确的。通过Tomcat加载此HTML,即通过

之类的URL加载

http://localhost:8080/.../xxx.html

如果由于某些原因您仍然希望在不使用Tomcat的情况下使用静态HTML,则将HTML中的servlet URL更改为完整的URL,如下所示:

<form action="http://localhost:8080/.../UploadBook" method="POST">

如果这不是您的情况,请提供更多信息,以及如何在浏览器中加载HTML。