Подключение Java-сервлета к JSP - PullRequest
0 голосов
/ 06 ноября 2019

Итак, я работаю над веб-приложением на Java, используя Google App Engine и Cloud SQL. У меня проблемы с созданием страницы регистрации. В моем файле JSP есть форма для страницы регистрации, и я хочу, чтобы она вызывала метод doPost моего сервлета. Видимо, по какой-то причине этого не происходит. Я не получаю никакой ошибки, но моя база данных не обновляется. Я следую этому руководству: https://cloud.google.com/appengine/docs/standard/java/building-app/handling-form-data.

Форма в моем JSP:

               <form method="POST" action="StudentSignUpServlet">
                    <div class="form-group">
                        <label for="first name"> First Name  </label>
                        <input type="text" class="form-control" name="firstName" id="firstName" aria-describedby="emailHelp" placeholder="ex: John">
                    </div>

                    <div class="form-group">
                        <label for="last Name"> Last Name </label>
                        <input type="text" class="form-control" name="lastName" id="lastName" aria-describedby="emailHelp" placeholder="ex: Smith">
                    </div>

                    <div class="form-group">
                        <label for="age"> Age </label>
                        <input type="text" class="form-control" name="age" id="age" aria-describedby="emailHelp" placeholder="ex: 15">
                    </div>


                    <div class="form-group">
                        <label for="school"> School </label>
                        <input type="email" class="form-control" name="school" id="school" aria-describedby="emailHelp" placeholder="High School">
                    </div>

                    <div class="form-group">
                        <label for="student grade"> Grade </label>
                        <input type="text" class="form-control" name="grade" id="grade" placeholder="ex: 11">
                    </div>

                    <div class="form-group">
                        <label for="emailInput"> Email address </label>
                        <input type="email" class="form-control" name="emailInput" id="emailInput" aria-describedby="emailHelp" placeholder="ex: johnSmith@iWorks.com">
                    </div>


                    <div class="form-group">
                        <label for="Password Input"> Password </label>
                        <input type="password" class="form-control" name="passInput" id="passInput" placeholder="Password">
                    </div>

                    <div class="form-group">
                        <label for="Confirm password"> Confirm Password </label>
                        <input type="password" class="form-control" id="confirmPass" placeholder="Confirm Password">
                    </div>

                    <div class="">
                        <a role="button" type="submit" class="btn btn-outline-primary">Sign Up</a>
                    </div>
                    <br>

                </form>

Мой класс сервлета:

@WebServlet(name = "StudentSignUpServlet", value = "/StudentSignUpServlet")
public class StudentSignUpServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {

    String firstName = req.getParameter("firstName");
    String lastName = req.getParameter("lastName");
    String school = req.getParameter("school");
    String emailInput = req.getParameter("emailInput");
    String passInput = req.getParameter("passInput");
    String age = req.getParameter("age");
    String grade = req.getParameter("grade");


    // Reuse the pool that was created in the ContextListener when the Servlet started.
    DataSource pool = (DataSource) req.getServletContext().getAttribute("my-pool");
    // [START cloud_sql_mysql_servlet_connection]
    // Using a try-with-resources statement ensures that the connection is always released back
    // into the pool at the end of the statement (even if an error occurs)
    try (Connection conn = pool.getConnection()) {


      PreparedStatement studentStmt = conn.prepareStatement(
          "INSERT INTO students (user_name, password, first_name, last_name, age, school, grade) VALUES (?, ?, ?, ?, ?, ?, ?);");
      studentStmt.setString(1, emailInput);
      studentStmt.setString(2, passInput);
      studentStmt.setString(3, firstName);
      studentStmt.setString(4, lastName);
      studentStmt.setString(5, age);
      studentStmt.setString(6, school);
      studentStmt.setString(7, grade);

      // Finally, execute the statement. If it fails, an error will be thrown.
      studentStmt.execute();

    } catch (SQLException ex) {
      // If something goes wrong, handle the error in this section. 
      resp.setStatus(500);
      resp.getWriter().write("Unable to successfully sign up!");
      System.out.println("Unable to successfully sign up!");// This is not being printed
    }
    // [END cloud_sql_mysql_servlet_connection]

    resp.setStatus(200);
    resp.getWriter().printf("Successfully signed up!");
    System.out.println("Successfully signed up!");// Neither is this being printed for some reason
  }

Я попытался обновить мойФайл web.xml для включения фрагмента ниже, но это не помогло.

<servlet>
    <servlet-name>StudentSignUpServlet</servlet-name>
    <servlet-class>iworks.StudentSignUpServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentSignUpServlet</servlet-name>
    <url-pattern>/StudentSignUpServlet</url-pattern>
  </servlet-mapping>

Любая помощь будет принята с благодарностью!

...