简体   繁体   中英

How to submit form values in JSON format to a servlet using AJAX?

I am trying to send login data in JSON format to a servlet using AJAX, but for some reason the servlet is getting null values. My servlet works fine when I send the data without AJAX, but when I use it it seems that my script is not getting any values.

Login form:

<form>
    <input class="input-container" type="text" placeholder="Enter Email" 
    name="email" required><br>
    <input class="input-container" type="password" placeholder="Enter Password" 
    name="paswd" required><br> 
   <input class="login-button" type="button" value="Log in" 
    onclick="loginAjax(this.form)">
</form>

AJAX:

function loginAjax(form) {
    var user = new Object();
    user.email = form.email.value;
    user.paswd = form.paswd.value;
    var jsonUser = JSON.stringify(user);
    console.log(user.email);
    console.log(user.paswd);
    console.log(jsonUser);
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("result").innerHTML = this.responseText;
            //Empty form fields
            form.email.value = "";
            form.paswd.value = "";
        }
    };
    xmlhttp.open("POST", "./login", true);
    xmlhttp.setRequestHeader("Content-type", "application/json");
    xmlhttp.send(jsonUser);
}

Servlet:

@ WebServlet(name = "login", urlPatterns = { "/login" })
    public class Login extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) 
                throws IOException, ServletException {
            response.sendRedirect("index.html");
    
        }
    
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response) 
                throws IOException, ServletException {
            response.setContentType(MediaType.APPLICATION_JSON);
            response.setCharacterEncoding("UTF-8");
    
            Dao dao = new Dao();
            
            // return values as string.
            String email = request.getParameter("email");
            String password = request.getParameter("paswd");
            
            System.out.println("Your email: " + email );// Delete Later!!
            System.out.println("Your password: " + password);// Delete Later!!
            System.out.println("Test passed0");
            // Read reference values from DB
            String salt = dao.getUserSalt(email);
            String hashpw = dao.getUserpasswordHash(email);
            System.out.println("Test 1 passed");
            dao.checkemail(email);
            try {
                System.out.println("Test 2 passed");
                if (SecurityUtils.isPasswordOk(hashpw, password, salt)) {
                    System.out.println("Test 3 passed");
                    String data = email;
                    HttpSession session = request.getSession();
                    User user = dao.readUserInfo(data);
                    dao.close();
                    System.out.println("Test 4 passed");
                    session.setAttribute("LoggedUser", user);
                    System.out.println("Session: " + request.getSession(false));
                    session.setMaxInactiveInterval(30 * 60);
                    System.out.println("Test 5 passed");
                    String encodedURL = response.encodeRedirectURL("/userInfo?email=" + data);
                    System.out.println("Final Test 6 passed");
                    try {
                        response.sendRedirect(encodedURL);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
    
                } else {
                    dao.close();
                    RequestDispatcher rd = getServletContext().getRequestDispatcher("./index.html");
                    try {
                        rd.include(request, response);
                    } catch (ServletException | IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
    
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }

The output I get on the console:

 Your email: null
 Your password: null
 java.lang.NullPointerException
 at security.SecurityUtils.getPasswordHashed(SecurityUtils.java:32)
 at security.SecurityUtils.isPasswordOk(SecurityUtils.java:57)
 at app.Login.doPost(Login.java:54)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:526)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:593)
 at org.eclipse.jetty.servlet.ServletHolder$NotAsync.service(ServletHolder.java:1459)
 at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
 at org.eclipse.jetty.servlet.ServletHandler$ChainEnd.doFilter(ServletHandler.java:1631)
 at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:148)
 at org.eclipse.jetty.servlet.FilterHolder.doFilter(FilterHolder.java:193)
 at org.eclipse.jetty.servlet.ServletHandler$Chain.doFilter(ServletHandler.java:1601)
 at ..Error continues...

I tried to switch the input type to submit and then added return false next to the onclick as the following onclick="loginAjax(this.form); return false" but that didn't help. I previously used similar ajax function with a form to send data to PHP and it worked fine. Any help would be much appreciated!

From the Documentation of XMLHttpRequest

XMLHttpRequest send() accepts an optional parameter which lets you specify the request's body; this is primarily used for requests such as PUT. If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null.

Apparently you are sending JSON data into your request body whereas you are expecting your data in request Parameter

String email = request.getParameter("email");
String password = request.getParameter("paswd");

Certainly it will return NULL

In this case you need to read request body from request.getInputStream()

Check this answer

try

  xmlhttp.open("POST","./login?email=" + user.email + "&paswd=" + user.paswd,false);
  xmlhttp.send();

instead of

xmlhttp.open('POST', './login', false);
xmlhttp.send(jsonUser);

OR YOU CAN USE JQUERY AJAX

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
  <script>
  
function loginAjax(form) {
    var user = new Object();
    user.email = form.email.value;
    user.paswd = form.paswd.value;
    var jsonUser = JSON.stringify(user);

     $.ajax({type: "POST",
    url:"./login",
    data:jsonUser,
    success:function(result){
    alert("Success");
    }
  });
}
</script>

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