简体   繁体   English

如何使用 AJAX 将 JSON 格式的表单值提交给 servlet?

[英]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.我正在尝试使用 AJAX 将 JSON 格式的登录数据发送到 servlet,但由于某种原因,servlet 正在获取 null 值。 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.当我在没有 AJAX 的情况下发送数据时,我的 servlet 工作正常,但是当我使用它时,我的脚本似乎没有得到任何值。

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: 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:我在控制台上得到的 output:

 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.我尝试将输入类型切换为提交,然后在 onclick 旁边添加return false ,如下所示onclick="loginAjax(this.form); return false"但这没有帮助。 I previously used similar ajax function with a form to send data to PHP and it worked fine.我以前使用过类似的 ajax function 和一个表格来将数据发送到 PHP 并且工作正常。 Any help would be much appreciated!任何帮助将非常感激!

From the Documentation of XMLHttpRequest来自XMLHttpRequest 的文档

XMLHttpRequest send() accepts an optional parameter which lets you specify the request's body; XMLHttpRequest send() 接受一个可选参数,让您指定请求的主体; this is primarily used for requests such as PUT.这主要用于诸如 PUT 之类的请求。 If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null.如果请求方法为 GET 或 HEAD,则忽略 body 参数,将请求正文设置为 null。

Apparently you are sending JSON data into your request body whereas you are expecting your data in request Parameter显然,您将 JSON 数据发送到您的请求正文中,而您期望您的数据在请求参数

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

Certainly it will return NULL当然它会返回NULL

In this case you need to read request body from request.getInputStream()在这种情况下,您需要从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或者您可以使用 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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