Table of Contents
Understand the interaction mechanism between HTML form submission and Servlet
The conflict points between client JavaScript verification and form submission
Correctly integrate JavaScript verification with Servlet submission
Backend Servlet processing logic
Summary and precautions
Home Java javaTutorial Strategies and practices for correctly calling Java Servlet after front-end JavaScript verification

Strategies and practices for correctly calling Java Servlet after front-end JavaScript verification

Aug 30, 2025 am 09:51 AM

Strategies and practices for correctly calling Java Servlets after front-end JavaScript verification

This article explains in detail how to correctly combine client JavaScript verification with back-end Java Servlet form submission logic in web development. We will explore the matching of HTML form submission mechanism, HTTP method (GET/POST) and Servlet doPost method, and provide sample code to guide developers to avoid common e.preventDefault() misuse and 405 errors, ensuring that the backend processing can be triggered smoothly after the front-end verification is passed.

In web application development, client JavaScript verification is an important means to improve user experience and reduce server pressure. However, how to correctly submit the authenticated user input to the backend servlet for further processing is a common problem for many developers. This tutorial will dig into the common pitfalls in this process and provide a standard set of solutions.

Understand the interaction mechanism between HTML form submission and Servlet

The HTML

element is the core mechanism for sending user input data to the server. Its two key attributes are:
  • action: Specifies the target URL for form data submission, usually a Servlet mapping path.
  • method: Specify the HTTP method used when submitting data. Common ones include GET and POST. For submissions involving data modifications or sensitive information such as login credentials, the POST method should usually be used.

Java Servlet responds to requests from different HTTP methods by overriding the doGet() or doPost() methods. If the form uses method="post", the Servlet needs to implement the doPost() method to handle the request. If the Servlet does not implement the corresponding HTTP method, the server will return a 405 Method Not Allowed error.

The conflict points between client JavaScript verification and form submission

When we bind a JavaScript event listener on the form's submit button, we need to pay special attention to event processing logic. The event.preventDefault() method is used to block the default behavior of events. For the click event of the form submit button or the submit event of the form, the default behavior is to trigger the form data to the URL specified by the action.

There are two main problems in the original code:

  1. Unconditional blocking of default behavior: In the JavaScript event listener, e.preventDefault() is placed after the verification logic and will be executed regardless of the verification result. This means that even if the client verification passes, the form's default submission behavior is blocked, causing the data to never be sent to the servlet.
  2. Incorrectly trying to redirect: Try to redirect using document.location.href = 'LoginServlet';. This method will trigger the browser to initiate a new HTTP GET request to the specified URL. Since LoginServlet only implements the doPost() method and does not have the doGet() method, the server returns a 405 Method Not Allowed error.

Correctly integrate JavaScript verification with Servlet submission

To correctly submit the form to the Servlet after client verification is passed, the key is to conditionally block the default behavior . e.preventDefault() is called only when client verification fails. If the verification is successful, the form is allowed to perform its default submission behavior.

Here is a modified JavaScript code example:

 <script>
    const formSubmit = document.getElementById("formSubmit");
    const loginForm = document.querySelector(".loginForm"); // Get form element formSubmit.addEventListener("click", (e) => {
        const Rno = document.getElementById("Rno").value;
        const Password = document.getElementById("pass").value;

        // Client verification logic if (Rno === null || Rno === "" || Password.length < 7) {
            alert("Please enter the room number or password incorrectly (at least 7 digits)");
            // The default submission behavior of the form is blocked only when the verification fails e.preventDefault(); 
            // You can choose whether to reload the page here, but it is usually not recommended to automatically refresh when verification fails // setTimeout(function () {
            // window.location.reload();
            // }, 5000);
        }
        // If the verification is passed, e.preventDefault() is not called to allow the form to be submitted naturally // The form&#39;s method="post" and action="LoginServlet" will take effect});

    // A better approach is to listen to the submit event of the form instead of the click event of the button // loginForm.addEventListener("submit", (e) => {
    // const Rno = document.getElementById("Rno").value;
    // const Password = document.getElementById("pass").value;
    // if (Rno === null || Rno === "" || Password.length < 7) {
    // alert("Please enter the room number or password incorrectly (at least 7 digits)");
    // e.preventDefault(); // Block form submission// }
    // });
</script>

In the above correction, e.preventDefault() is only executed if the if condition (i.e., verification failure) is true. If the verification is passed, e.preventDefault() will not be called, and the form will send a POST request to the LoginServlet as defined in its

.

Backend Servlet processing logic

The doPost method of the backend LoginServlet will be responsible for receiving and processing this POST request.

 import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginServlet() {
        super();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8"); // Set response content type and character encoding PrintWriter out = response.getWriter();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");

            // Get the form parameter int roomNo = Integer.parseInt(request.getParameter("Roomno"));
            String password = request.getParameter("password");

            PreparedStatement ps = con.prepareStatement("select * from login where roomNo=? and password=?");
            ps.setInt(1, roomNo);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();

            if(rs.next()) {
                int userRoom = rs.getInt(1);
                String userName = rs.getString(3);
                out.println("RoomNo:" userRoom " is allocated to " userName);
                // After logging in successfully, page redirection or session information will usually be performed// response.sendRedirect("welcome.jsp"); 
            } else {
                out.println("Failed to log in");
                // If the login fails, you can redirect back to the login page and display an error message // request.setAttribute("errorMessage", "Error username or password");
                // request.getRequestDispatcher("Login.jsp").forward(request, response);
            }
            con.close();

        } catch (ClassNotFoundException e) {
            out.println("Database driver loading failed: " e.getMessage());
            e.printStackTrace();
        } catch (SQLException e) {
            out.println("Database operation failed: " e.getMessage());
            e.printStackTrace();
        } catch (NumberFormatException e) {
            out.println("The room number format is incorrect: " e.getMessage());
            e.printStackTrace();
        } finally {
            out.close(); // Make sure PrintWriter is closed}
    }

    // If you need to process GET request, implement the doGet method// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // // For example, forward directly to the login page // request.getRequestDispatcher("Login.jsp").forward(request, response);
    // }
}

In the Servlet, we added response.setContentType("text/html;charset=UTF-8"); to ensure the correct encoding of the response, and to add the handling of NumberFormatException to deal with the case where room numbers are entered into non-numbers. In actual applications, after successful login, page redirect (response.sendRedirect()) is usually performed to the user's homepage, rather than directly outputting text. When login fails, you should also consider redirecting back to the login page and displaying specific error messages.

Summary and precautions

  1. Conditional e.preventDefault(): This is the core of solving the problem of form submission after client verification. The default submission behavior of the form is blocked only when the verification fails.
  2. Match HTTP methods: Make sure that the method attribute of the HTML form matches the doGet() or doPost() methods implemented in the Servlet. For form submissions, POST is usually used.
  3. Avoid misuse of document.location.href: Modifying document.location.href directly triggers a GET request, which is not applicable to scenarios where POST data is required and may result in a 405 error.
  4. Server-side verification is indispensable: Client-side verification only provides convenience for user experience and cannot replace strict server-side verification. All data from the client must be verified and disinfected again on the server side to prevent security vulnerabilities.
  5. Error handling and user feedback: Whether on the client or the server, a clear user feedback mechanism should be provided. A prompt pops up when the client fails to verify, and an error message is displayed or redirects to the error page when the server fails to process.
  6. Asynchronous commit (AJAX): For more complex interactions, such as logging in without refreshing the page, you can consider using AJAX (fetch API or XMLHttpRequest) for asynchronous data submission. This provides greater flexibility, but the implementation is also relatively complex.

By following these principles, developers can effectively integrate client-side JavaScript verification with the form submission process of backend Java Servlets to build robust and user-friendly web applications.

The above is the detailed content of Strategies and practices for correctly calling Java Servlet after front-end JavaScript verification. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to join an array of strings in Java? How to join an array of strings in Java? Aug 04, 2025 pm 12:55 PM

Using String.join() (Java8) is the easiest recommended method for connecting string arrays, just specify the separator directly; 2. For old versions of Java or when more control is needed, you can use StringBuilder to manually traverse and splice; 3. StringJoiner is suitable for scenarios that require more flexible formats such as prefixes and suffixes; 4. Using Arrays.stream() combined with Collectors.joining() is suitable for filtering or converting the array before joining; To sum up, if Java8 and above is used, the String.join() method should be preferred in most cases, which is concise and easy to read, but for complex logic, it is recommended.

How to implement a simple TCP client in Java? How to implement a simple TCP client in Java? Aug 08, 2025 pm 03:56 PM

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

How to compare two strings in Java? How to compare two strings in Java? Aug 04, 2025 am 11:03 AM

Use the .equals() method to compare string content, because == only compare object references rather than content; 1. Use .equals() to compare string values equally; 2. Use .equalsIgnoreCase() to compare case ignoring; 3. Use .compareTo() to compare strings in dictionary order, returning 0, negative or positive numbers; 4. Use .compareToIgnoreCase() to compare case ignoring; 5. Use Objects.equals() or safe call method to process null strings to avoid null pointer exceptions. In short, you should avoid using == for string content comparisons unless it is explicitly necessary to check whether the object is in phase.

How to send and receive messages over a WebSocket in Java How to send and receive messages over a WebSocket in Java Aug 16, 2025 am 10:36 AM

Create a WebSocket server endpoint to define the path using @ServerEndpoint, and handle connections, message reception, closing and errors through @OnOpen, @OnMessage, @OnClose and @OnError; 2. Ensure that javax.websocket-api dependencies are introduced during deployment and automatically registered by the container; 3. The Java client obtains WebSocketContainer through the ContainerProvider, calls connectToServer to connect to the server, and receives messages using @ClientEndpoint annotation class; 4. Use the Session getBasicRe

Correct posture for handling non-UTF-8 request encoding in Spring Boot application Correct posture for handling non-UTF-8 request encoding in Spring Boot application Aug 15, 2025 pm 12:30 PM

This article discusses the mechanism and common misunderstandings of Spring Boot applications for handling non-UTF-8 request encoding. The core lies in understanding the importance of the charset parameter in the HTTP Content-Type header, as well as the default character set processing flow of Spring Boot. By analyzing the garbled code caused by wrong testing methods, the article guides readers how to correctly simulate and test requests for different encodings, and explains that Spring Boot usually does not require complex configurations to achieve compatibility under the premise that the client correctly declares encoding.

Exploring Common Java Design Patterns with Examples Exploring Common Java Design Patterns with Examples Aug 17, 2025 am 11:54 AM

The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.

See all articles