0

Im trying to get values from my request but it return null. What is the problem?

This is my form:

    <form class="register-form">
        <input class="name" type="text" placeholder="name"/>
        <input class="password" type="password" placeholder="password"/>
        <button id="register">create</button>
    </form>

My post method:

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        String name = req.getParameter("name"); 
        if (Objects.isNull(projectService.getByName(name))) {
            logger.info("Registration new project " + name); //NAME == NULL ???
            String password = req.getParameter("password");
            int budget = Integer.parseInt(req.getParameter("budget"));

         ...

        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write("Success");
    }

And JS part:

$(document).ready(function () {
    $("button#register").click(function () {
        var name = $("form.register-form input.name").val();
        var password = $("form.register-form input.password").val();
        if (name == '' || password == '') {
            alert("Please fill all fields...!!!!!!");
        }  else {
            var projectRegistration = {
                projectName: name,
                projectPassword: password
            };
            $.post("registration", projectRegistration, function (data) {
                if (data === 'Success') {
                    $("form")[0].reset();
                }
            });
        }
    });
});

Im using Tomcat ver 8.5.56

Carlos Bazilio
  • 830
  • 9
  • 20

2 Answers2

1

The root cause of the problem is that you are not passing any parameter with the name, name because you do not have an input field with the name, name.

Replace

<input class="name" type="text" placeholder="name"/>

with

<input class="name" type="text" placeholder="name" name="name"/>
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • I think that my answer and yours are together the cause, don't you think? The request is made by JS code, which passes the projectRegistration object. This object doesn't have a field name also. – Carlos Bazilio Jul 02 '20 at 21:41
  • @CarlosBazilio - You are right. Thanks for asking OP to consider this answer as well. – Arvind Kumar Avinash Jul 03 '20 at 08:33
0

At JS code you are building an object projectRegistration which is passed to post request. This object has keys projectName and projectPassword which should be used inside the servlet:

String name = req.getParameter("projectName");

Hope it helps.

Carlos Bazilio
  • 830
  • 9
  • 20