简体   繁体   中英

How to check if form was submitted in Java

I have a form in jsp:

<form id="emailForm" data-role="form">
      <input type="text" class="form-control" id="name" name="name" placeholder="Enter full name..">
   <input type="submit" id="emailSubmit" name="emailSubmit" class="btn btn-default" value="submit">
</form>

I send the form to controller using AJAX:

$("#emailSubmit").click(function(e){
        e.preventDefault(); //STOP default action
    var postData    = $("#emailForm").serializeArray();
        $.ajax(
            {
                type: "POST",
                url : "HomeController",
                data : postData,
                success: function(data) 
                {
                    $("#emailResult").html("<p>Thank your for submitting</p>);

                },
                error: function(jqXHR, textStatus, errorThrown) 
                {
                    $("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
                }
            });
});

I check if it has been submitted in Controller here:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String emailSubmit = request.getParameter("emailSubmit");

    if(emailSubmit != null){
        // continue
    }}

Can someone please tell me why when it checks if form was submitted in the controller that it is null ?

For forms the standard way is to catch the submit event instead of the click event of the button:

$("#emailForm").submit(function(e){
    e.preventDefault();
    var postData = $(this).serializeArray(); // or: $(this).serialize();
    $.ajax({
        type: "POST",
        url : "HomeController",
        data : postData,
        success: function(data) 
        {
            $("#emailResult").html("<p>Thank your for submitting</p>);

        },
        error: function(jqXHR, textStatus, errorThrown) 
        {
            $("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
        }
    });
});

I have tried several methods to be able to check the submit button isn't null and can't solve that issue. For now I have set a hidden input field in the form like so:

<input type="hidden" name="form" value="contactForm">

In controller I check for the form:

String form     = request.getParameter("form");
    if(form.equals("contactForm")){
        // continue
    }

Doing this enables me to know which form has been posted to the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM