0

I am trying to write my first JSON servlet as following:

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.json.JSONException;

public class Home extends HttpServlet{  

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{      
        res.setContentType("text/html; charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");      
        StringWriter sWriter    = new StringWriter();  
        PrintWriter out         = new PrintWriter(sWriter);                     

        String jsonText         = "{\"Name\":\"Vahid\",\"Nickname\":null,\"Salary\":\"15000.0\",\"isPermanent\":true,\"EmployeeId\":\"121\"}";      
        try{
            JSONObject json = new JSONObject(jsonText);       
            String name = json.getString("Name");
            out.println(json.toString()+"<br>"+"Name = "+name);
        }catch(JSONException e){
            e.printStackTrace();
        }

        res.getWriter().print(sWriter.toString());
        out.flush();
        out.close();
    }//doGet        
}//class

This code is working fine and giving me this output:

{"Name":"Vahid","Nickname":null,"Salary":"15000.0","EmployeeId":"121","isPermanent":true}
Name = Vahid

My question is how can I get JSON Object as a whole (as POST request) in my servlet from client browser e.g. request.getParameter("?????"); //what will be parameter name of JSON object? OR I have to get one by one all elements of JSON object as request.getParameter("name");

UPDATE
Here is my html file:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <script type="text/javascript" src="/js/jquery.min.js"></script>
    <script>
var form = $('#form1');
$(document).ready(function(){
     $('body').hide().fadeIn(5000);
$(".submit").click(function (e) {

$.ajax({
type: form.attr('method'),
url: form.attr('action'),
console.log(url);
data: $(form).serialize(),
         success: function(msg){

             var json = msg ;
             $('#json').val(json);   
                            }
        });

                                 });
                             });
</script>


<body><br>
<form name="input" action="/JSONServlet"  method="POST" id="form1"  enctype="text/plain">
First name: <input type="text" name="FirstName" id="Firstname" value=" "><br>
Last name: <input type="text" name="LastName" value=" "><br>
<br>
<input type="submit" value="Submit" class="submit">

</form>
</body>

When I write String name = request.getParameter("name"); then output is null

Here what am trying:

String name = request.getParameter("FirstName");
    System.out.println(name);
        PrintWriter out= response.getWriter();
        try{
            JSONObject json = new JSONObject(name);         
            out.println(json.get("name"));          
        }catch(JSONException e){
            e.printStackTrace();
        }

output is null

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Devdas
  • 69
  • 1
  • 2
  • 10

2 Answers2

2

It depends on which technology you are using to send the POST request. Below is a javascript example to send the json data:

var data = {
  name : "Vahid"
};
var request = new XMLHttpRequest();
request.open("POST", <URL>, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

request.send(JSON.stringify(data));

Update

Once you send the data, you can use request.getParameter() on the server side to retrieve it, e.g.:

String data = request.getParameter("param_name");

This will give you String representation of the json. You can then convert it into JSONObject like you have done in the example in question.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

OR I have to get one by one all elements of JSON object as request.getParameter("name");

Yes, if you pass a json object to the Servlet, you can get the individual field names like you normally do. One by one.

When I write String name = request.getParameter("name"); then output is null

This is because you are getting the wrong parameter.

Look at your form:

First name: <input type="text" name="FirstName" id="Firstname" value=" "><br>
Last name: <input type="text" name="LastName" value=" "><br>

To get the first name field you must call 'FirstName' (name attribute).

So do this:

String name = request.getParameter("FirstName");

You also don't need

value=" "

or

id="FirstName"

Just do:

<form name="input" action="/JSONServlet"  method="POST" id="form1">
First name: <input type="text" name="FirstName"/><br>
Last name: <input type="text" name="LastName"/><br>
<br>
<input type="submit" value="Submit" class="submit">
</form>

remove this also from form tag:

enctype="text/plain"

Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44
  • thanks @Jonathan. You said Yes,` if you pass a json object to the Servlet, you can get the individual field names like you normally do. One by one.` My question is before this step i.e. how can I get `{"email":"vahid@gmail.com","name":"Vahid","Code":"101","info":"Success"}` in servlet then I shall split it – Devdas Aug 24 '17 at 16:29