简体   繁体   中英

how to get the form data in JSON format in servlet

My html code is

<form action="/FirstServlet/Profile" method="post"  class="login">
    UserName: <input type="text"  id="uName" name="name"><p>
    Password: <input type="password"  id="password" name="password"><br>
    <input type="submit" id="button" value="login">
</form>

and the javascript code is

<script  src="js/jquery-3.2.1.min.js"></script>
<script  src="js/jquery.serializeObject.js"></script>
<script  src="js/Gruntfile.js"></script> 
<script>
   $(document).ready(function(){
            var form=$('form.login').serializeObject();
            alert(form);
            form.submit(function(){
                $.ajax({
                    type:form.attr('method'),
                    url:form.attr('action'),
                    dataType:'json',
                    data:Json.stringify(form),
                    success:function(data){

                    }
                });
            });

        });
</script>

But still I get the answer in this format

name=zeeshan&password=zeeshan@123

I want to get the answer in json format like:

{"name":"zeeshan","password":"zeeshan@123"}

My servlet code of getting the data

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

    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));


    String json = "";
    if(br != null){
        json = br.readLine();
    }
    System.out.println(json);
}

I've searched a lot, every where they say that the output of this code is in json, but practically I didn't get it in that format.

How can I get my output to be in JSON format?

看来您在发送前将其加密了,这可能是问题所在

You may try this workaround, in javascript:

 data:{'json':JSON.stringify($(form).serializeArray())},

In servlet:

String json=request.getParameter("json");

Edited:

 data:{'json':JSON.stringify($(form).serializeObject())},

Change

<input type="submit" id="button" value="login">

to

<input type="button" id="button" value="login">

Clicking on input type submit, submits the form directly and reloads the page and hence your script is never called.

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