2

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(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        new JavaHttpUrlConnectionReader();

  }

/*I could add all the content in servlet itself but I have done it in separate class  JavaHttpUrlConnectionReader*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;


class JavaHttpUrlConnectionReader {


    public JavaHttpUrlConnectionReader()
  {
    try
    {
      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);
    }
  }


/*i m doing this by calling a method doHttpUrlConnectionAction*/

    private void doHttpUrlConnectionAction(String myUrl) throws Exception {

        URL url = null;
    BufferedReader reader = null;
    StringBuilder stringBuilder;
 JSONParser jsonParser = new JSONParser();

    try
    {
      // create the HttpURLConnection
      url = new URL(myUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      // just want to do an HTTP GET here
      connection.setRequestMethod("GET");

      // uncomment this if you want to write output to this url
      //connection.setDoOutput(true);

      // give it 15 seconds to respond
      connection.setReadTimeout(15*1000);
      connection.connect();

      // read the output from the server


      reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

      String name = (String) jsonObject.get("name");
      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);

    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw e;
    }

    finally
    {

      if (reader != null)
      {
        try
        {
          reader.close();
        }
        catch (IOException ioe)
        {
          ioe.printStackTrace();
        }
      }
    }
    }
}

I am getting the following output. Can anyone help? enter image description here

OneCricketeer
  • 126,858
  • 14
  • 92
  • 185

4 Answers4

1

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.

ernest_k
  • 39,584
  • 5
  • 45
  • 86
  • request body is different from request parameter... your comment about using post instead of get is correct for two reasons 1. data changes in the server end - so it should be post 2. http get - request body can be ignored - ref http://stackoverflow.com/questions/978061/http-get-with-request-body – Balaji Krishnan Feb 08 '16 at 13:44
  • thanks alot for replying guyz...but when i m using post method...i m getting response as error[object Object] in the alert and 500 internal server error in the servlet – Aditya Khadilkar Feb 09 '16 at 06:16
  • previously i was using post only but due to this error i used get..plzz help guyz – Aditya Khadilkar Feb 09 '16 at 06:17
  • @Ernest Kiwele I tried It....I still can't print the values...and there is a json data on the server....I think I don't I will directly be able to fetch those values from server with request.get parameter.....is there any other solution to fetch json data from localhost and convert it to string..???? – Aditya Khadilkar Feb 09 '16 at 06:40
  • Please help clarify the scenario: I see a javascript-based client that is posting data to a server at "http://localhost:8080/jsondem/pass". My understanding was/is that the code snippet of a servlet doPost/doGet method belongs to the servlet exposed in a webapp at that url (http://localhost:8080/jsondem/pass), which made me asume that JavaScript code was calling the servlet. As the servlet/java code is firing an http call to "http://localhost:8080/jsondem/pass", that means that it is NOT the one receiving the data. Do you have a second web server? Please clarify my understanding. – ernest_k Feb 09 '16 at 07:27
  • @ErnestKiwele ur assumption is almost right..javascript is posting data on the data...and i want to fetch that data from the localhost server..which i am unable to do. – Aditya Khadilkar Feb 09 '16 at 07:48
  • @ErnestKiwele basically i m new to java....as far as server is concerned i m using glassfish v4.1....and i dont exactly know about the web server...i m not using any i guess – Aditya Khadilkar Feb 09 '16 at 07:51
  • @ErnestKiwele the thing is i want to add that data into the database....when i connected the database in the servlet ...a blank entry was made in the database....so i am getting a response...but i am getting a blank response...if u have any other technique to do it tell me – Aditya Khadilkar Feb 09 '16 at 07:53
  • Here is an example of jQuery/servlet found on GitHub: https://github.com/jorgechavez77/jquery-project. The client side uses jQuery to post data as you did. That code is in the jsp (web-app/src/main/webapp/index.jsp). The server side uses a servlet (https://github.com/jorgechavez77/jquery-project/blob/master/web-app/src/main/java/web/app/servlet/AjaxServlet.java) to read the message and print it to the console. Please use this as an example to read all the values that the form submits and save in DB. Please note that the project isn't mine and I'm suggesting it just as an example. – ernest_k Feb 09 '16 at 08:01
  • Another glassfish example can be found here: https://docs.oracle.com/cd/E17952_01/connector-j-en/connector-j-usagenotes-glassfish-config-servlet.html. To get better understanding of the Java servlet method implementations, see the relevant documentation here: http://docs.oracle.com/javaee/6/tutorial/doc/bnafv.html#bnafw. Hope that helps. – ernest_k Feb 09 '16 at 08:06
  • @ErnestKiwele i tried technique which u proposed.....but it is not that helpful in what i require in my project...sir, my json data is on the localhost..can u tell me a way to fetch the elements from that json data and print them in either alert or anything....it will be helpful in what i m trying to achieve.. – Aditya Khadilkar Feb 09 '16 at 10:34
0

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!=null){
            System.out.println("read line is " + s);
            s = br.readLine();
        }
        br.close();
    }   
}

output in console : read line is {"name":"a","password":"d","mobileNo":"b","emailId":"c"}

If for some reason, you dont want to use servlets and intend to handle directly using URLConnection, post the stacktrace you get.

Balaji Krishnan
  • 967
  • 3
  • 11
  • 28
  • sir I tried it...at first I got sending:{"name":"aditya","password":"ddsgfsgf","mobileNo":"8108345911","emailId":"ad@gmail.com"} but then i was getting a big error in the alert....i m posting a pic of that error below sir...plz check it – Aditya Khadilkar Feb 10 '16 at 12:10
  • that image is after my post sir...it starts with localhost 8080 says..plzz check it out – Aditya Khadilkar Feb 10 '16 at 12:18
0

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();

}
Hamdi Douss
  • 891
  • 7
  • 15
  • I tried what u said....I m still not getting any output.....my code in the doGet method is as follows `String queryString = request.getQueryString(); JSONObject jo = new JSONObject(queryString); String name = jo.getString("name"); String password = jo.getString("password"); String mobileNo= jo.getString("mobileNo"); String emailId = jo.getString("emailId"); PrintWriter writer = response.getWriter(); writer.write(""+name+" "+password+" "+mobileNo+" "+emailId+"");` – Aditya Khadilkar Feb 11 '16 at 05:42
  • try to add : `writer.close()` at the end. – Hamdi Douss Feb 11 '16 at 12:02
  • u gave me some good inputs...I tried them...but still it is not working....can u tell me another technique to do this task...?? – Aditya Khadilkar Feb 15 '16 at 05:17
  • What are you getting exactly ? Could you repost your entire code at this step ? – Hamdi Douss Feb 15 '16 at 14:39
  • i have uploaded the output previously...refer it on the top of this page...i m getting blank response object...and my code is same as posted above in the comments..refer these things and suggest something plzz...i m stuck with this for a long time – Aditya Khadilkar Feb 16 '16 at 10:34
0

<?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

  • @Balaji Krishnan it is showing many servlet entries because I tried different servlet codes in separate servlets and ran them....plzz help if u can – Aditya Khadilkar Feb 11 '16 at 05:58