0

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!

10
  • Have you checked your jsonUser variable in JS Code.Is it getting data correct? Commented Aug 15, 2022 at 6:49
  • Can't you do console.log() in AJAX or other debugging methods Commented Aug 15, 2022 at 7:17
  • @Manik Sorry I actually checked and I think I am getting it correctly as :{"email":"[email protected]","paswd":"DonaldTrump"} Commented Aug 15, 2022 at 7:19
  • Then please accept the answer and close the issue Commented Aug 15, 2022 at 7:21
  • My servlet is still getting null values and my issue is not solved sir! Commented Aug 15, 2022 at 7:23

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to modify the script to send data as parameter instead of JASON?
I won't recommend you to send sensitive data [password] in request parameter. This is not a good practice unless you are applying any cryptographic algorithm. You can use AJAX.
0

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>

8 Comments

When I applied the first option it some how loads the target page in the index.html instead of redirecting. Is the issue in my servlet. And the second option somehow isn't working, but I'll keep trying to get something to work.
And can the values in the sendDataToServerWithJquery(value1,value2) be replaced with just sendDataToServerWithJquery(form)?
yes you can replace sendDataToServerWithJquery parameters with your parameters as I have edited the answer
For the first approach did you just replace only 2 lines, no more lines should be removed or replaced
When I try the second approach nothing at all happens. And yes I only replaced the 2 lines you suggested but still the target page loads with the login page.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.