Aditya Khadilkar February 2016

how to decode json data in java (how to fetch json data from localhost and print its values)

I am trying to perform a simple json encoding and decoding example with Java.

In this example I am sending signup page details to a Javascript. In Javascript I am encoding those values in json format and sending them to a servlet.

I don't know exactly where I'm going wrong but I'm unable to decode (parse) and print that data at the servlet end.

I'm new to json and Java and I just want to first print values from a json array in a servelet so that I can later put them in a database.

/*this is my javascript code*/

function signup()
{
   var request = createCORSRequest( "GET", "http://localhost:8080/jsondem/pass" );
  /*pass is the servlet*/
    var name = document.getElementById('name').value;
    var mobileNo = document.getElementById('mobileNo').value;
    var emailId = document.getElementById('emailId').value;
    var password = document.getElementById('password').value;
    alert(name);
    alert(mobileNo);
    alert(emailId);
    alert(password);
  /*i m just printing values for cross checking*/

    var data ={"name":name,"password":password,"mobileNo":mobileNo,"emailId":emailId};
    
	alert(JSON.stringify(data));
	var sendData = function(data){   
	alert(JSON.stringify(data));
      $.ajax({
     url:'http://localhost:8080/jsondem/pass',
     type: 'GET',
     contentType: 'application/json',
    data: JSON.stringify(data),
	success: function(response)
	{
            alert(response);
	},
        error: function(response)
        {
          alert('error'+response);
        }
});
};
sendData(data);
}

Following is my servlet where I want to take the json data uploaded on localhost into a servlet and I want to print it

/*this is my servlet's doGet Method*/
protected void doGet(HttpServletReque        

Answers


Ernest Kiwele February 2016

Your JavaScript is submitting code to the server. On the server side (in the servlet), you need to read the data in the doGet method. You wouldn't "connect" to the server again. Here is an example of the doGet method implementation:

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

    String name = request.getParameter("name");
    String password = request.getParameter("password");
    String mobileNumber = request.getParameter("mobileNo");
    //And so on...
}

Additionally, as you're sending data to the server, you'd rather use the POST http method and, in the servlet, implement doPost instead of doGet.


Balaji Krishnan February 2016

Do not use HTTP GET request when you intend to change the server state - updates to data.

step1: so your $.get should be $.post step2: verify if the request is properly sent - you can use many tools. I prefer chrome developer console - use network tab to view the request parameters and payload. step3: read the values sent in the server side

Corrections: steps1 & step2: I tried your java script code - request is being sent properly. just a slight modification of your code :

function signup() {
        var name = document.getElementById('name').value;
        var mobileNo = document.getElementById('mobileNo').value;
        var emailId = document.getElementById('emailId').value;
        var password = document.getElementById('password').value;
        var data = {
            "name" : name,
            "password" : password,
            "mobileNo" : mobileNo,
            "emailId" : emailId
        };
        var sendData = function(data) {
            alert("sending: " + JSON.stringify(data));
            $.ajax({
                url : 'http://localhost:8080/jsondem/pass',
                type : 'POST',
                contentType : 'application/json',
                data : JSON.stringify(data),
                success : function(response) {
                    alert(response);
                },
                error : function(response) {
                    alert('error' + JSON.stringify(response));
                }
            });
        };
        sendData(data);
    }

step3: Here is the code i used to test using servlet

@WebServlet(urlPatterns={"/pass"},name="testServlet")
public class TestServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("got the request");
        BufferedReader br = req.getReader();
        String s = br.readLine();
        while(s! 


Hamdi Douss February 2016

On the server side, you are trying to reconnect to the server. You should read about the servlet model in Java and know how to implement a proper servlet, and how to read parameters from the client request. Your client (javascript) implementation is OK. It sends a proper request to http://localhost:8080/jsondem/pass with a JSON body (though it should use POST method). But your server implementation is wrong:

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

    new JavaHttpUrlConnectionReader();

}

You should read the data here (above) from the request object.

String myUrl = "http://localhost:8080/jsondem/pass";
  // if your url can contain weird characters you will want to 
  // encode it here, something like this:
  myUrl = URLEncoder.encode(myUrl, "UTF-8");

 doHttpUrlConnectionAction(myUrl);

}
catch (Exception e)
{
  System.out.println(e);
}

Here (above) you are trying to connect from the server side to the server again. I don't think this is what you wanted to do.

System.out.println("Name: " + name);

long mobileNo = (long) jsonObject.get("mobileNo");

System.out.println("Mobile Number: " + mobileNo);

String emailId = (String) jsonObject.get("emailId");
System.out.println("Email Id: " + emailId);


String password = (String) jsonObject.get("password");
System.out.println("password: " + password);

I think you wanted to return strings to the client. System.out.println does not send back anything to the client. It prints out on the server side console. You should instead write on the response object below:

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

    new JavaHttpUrlConnectionReader();

}


Aditya Khadilkar February 2016

enter image description here

@Balaji Krishnan plzz do check it out sir...and suggest something


Aditya Khadilkar February 2016

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>pass</servlet-name>
        <servlet-class>pass</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>TestServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>pass1</servlet-name>
        <servlet-class>pass1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>pass</servlet-name>
        <url-pattern>/pass</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/TestServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>pass1</servlet-name>
        <url-pattern>/pass1</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

check this out @Balaji Krishnan

Post Status

Asked in February 2016
Viewed 1,602 times
Voted 6
Answered 5 times

Search




Leave an answer