简体   繁体   中英

I use java Servlets and cannot redirect to another page after submitting form and sending data in JSON format

I don't have a lot experience in web developing.

I want to sent form data in request body in JSON format. When server reсieve data it should register new user and redirect user to another page with user's data. Deserializing and ragistration into database works good. The main problem is that after sending form data to the server the page recieve response with new page(url and content), but just in headers and doesn't change. How can I change the page after sending form data??

Here is Javascript handling and HTML code of form:

<script>
function makeJSON(form) {

    var userData = {

        "phone_number" : form.phone_number.value,
        "country" : form.country.value,
        "city" : form.city.value,
        "date_of_birth" : form.date_of_birth.value,
        "email" : form.email.value,
        "sex" : form.sex.value,
        "login" : form.login.value,
        "password" : form.password.value

    };

    var requestString = JSON.stringify(userData);

    var request = new XMLHttpRequest();

    request.open("POST", "/registration");
    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    request.send(requestString);

}

<div id="topNavLine"></div>

<div class="regBody">
    <div class="regFormTop"><h1>Registration form</h1></div>
    <form id="registration" method="post" onsubmit="makeJSON(this);" enctype="application/x-www-form-urlencoded">
        <fieldset>
            <legend>Personal data</legend>
            <p><label>Phone:</label><input name="phone_number" type="text" form="registration"></p>
            <p><label>Country:</label><input name="country" type="text" form="registration"></p>
            <p><label>City:</label><input name="city" type="text" form="registration"></p>
            <p><label>Date:</label><input name="date_of_birth" type="date" form="registration"></p>
            <p>
                <Label>Email:</Label><input name="email" type="text" form="registration"></p>
            <p><label>Sex:</label>
                M<input type="radio" name="sex" value="male">
                F<input type="radio" name="sex" value="female">
            </p>
        </fieldset>
        <fieldset>
            <legend>Login data</legend>
            <p><label>Login:</label><input name="login" type="text" form="registration"></p>
            <p><label>Password:</label><input name="password" type="password" form="registration"></p>
            <p><label>Confirm password:</label><input name="passwordValidation" type="password" form="registration"></p>
        </fieldset>

        <div class="regButton">
            <button class="regButton" type="submit"  form="registration">Register</button>
        </div>

    </form>
</div>

Here is doPost servlet method:

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


    String str = request.getReader().lines().collect(Collectors.joining());

    System.out.println(str);

    UserRegData userRegData = new ObjectMapper().readValue(str,UserRegData.class);

    long tmpId = new Random().nextLong();
    if (tmpId < 0) {
        tmpId *= -1;
    }
    userRegData.setId(tmpId);
    userRegData.printUser();

    try (Connection connection = ConnectionWithDB.connectToDB()) {

        ManagingData.setRegistrationData(userRegData, connection);

    } catch (SQLException e) {
        e.printStackTrace();
    }

    response.setStatus(201);
    response.sendRedirect("/page_of_user");

}

The whole approach is a bit wrong IMHO. The response should be handle by a callback function in javascript. If there are validation errors for example you can show them in the same form. If all is succesful then in javascript you call 'page_of_user'.

Here is JQuery in action:

$.ajax({
        type: "POST",
        url: "/registration",
        data: userData ,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){ document.location.href='/page_of_user'; },
        failure: function(errMsg) {
            alert(errMsg);
        }
  });

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