How to send and receive json data betweeen javascript and servlet?
NickName:onlycparra Ask DateTime:2019-05-25T13:08:34

How to send and receive json data betweeen javascript and servlet?

The Problem

I cannot get to work the communication between a client with html/javascript sending the data of a form as json to a servlet, and then, the servlet replaying json back. I don't exactly know where I am doing the mistake(s).

The idea is this:

  • JavaScript takes the data from a form, parse it to json, and send it to the servlet.
  • In the server side, the servlet reads the json sent, take some action. Produce another json, and replay it.
  • Back in the client, read the json and draw some html based on that. (For now, I am just console.log()-ing it)

The client

A javascript code that gets data from a element:

//first I add the listener
document.querySelector('#login_form').addEventListener('submit',(e)=>{
    e.preventDefault();
    login_send(e.target);
});
//then the function to run on submit
function login_send(form){
    console.log(form2json(form));
    //I get the content: {"email":"[email protected]","pass":"aoeu"}
    fetch('login',{
        method:'POST',
        headers:{
            'Accept':'application/json, text/plain, */*',
            'Content-type':'application/json'},
        body: form2json(form)
    })
    .then((res) =>res.json())
    .then((data) => {
        console.log("I got: "+data);//for now, just printing the data
    })
    .catch((err) => console.error(err));
}
//this is my handcrafted "form to json" string formatter,
//surely there is a better (correct?) way of doing it.
function form2json(form){
    let js="{";
    let last=form.length-1;
    for (i=0;i<last;i++){
        js+="\""+form.elements[i].name+"\":\""+form.elements[i].value+"\"";
        if(i+1<last) js+=",";
    }
    js+="}";
    return js;
}

The server

The web.xml file, to wire the url to the java class:

<?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>Login Servlet</servlet-name>
        <servlet-class>com.cactusstore-1.ui.Login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login Servlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

The servlet I redirect doGet() and doPost() to processRequest(), as given by default in Netbeans when you create a new "Web application".

...
import javax.json.*;
...
public class Login extends HttpServlet {
    protected void processRequest(HttpServletRequest req,
            HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("application/json;charset=UTF-8");
        try (PrintWriter out = res.getWriter()) {
            //an object with three fields.
            User u = new User(
                    req.getParameter("email"),
                    "10010099",
                    req.getParameter("pass")
            );
            //construct json answer.
            //based on https://www.youtube.com/watch?v=BPMVC999HTs
            JsonObject root;
            JsonObjectBuilder rootBuilder = Json.createObjectBuilder();
            JsonObjectBuilder userBuilder = Json.createObjectBuilder();
            userBuilder
                    .add("name",u.getName())
                    .add("email", u.getEmail())
                    .add("sid", u.getSId());

            root = rootBuilder.add("login", userBuilder).build();
            //write response to out
            out.println(root);
            out.flush();
            out.close();
        }
    }
}

I expect to get the json, but I get this error:

custom.js:23 SyntaxError: Unexpected end of JSON input

It looks like my servlet is returning nothing. If I change the res.json(), with res.text(), I get nothing. If I change the out.println(root) with out.println("{\"name\":\"John\"}");, I still get nothing.

Thanks :) (please be kind, this is my first time on all this languages. And I am already confused).


Edit 1

Class User Adding the class for completeness.

public class User {
    private String email;
    private final String session_id;
    private String name;
    public User(String email, String id, String name) {
        this.email = email;
        this.session_id= id;
        this.name = name;
    }
    public String getName() {return name;}
    public String getEmail(){return email;}
    public String getSId()  {return session_id;}
    public void   setName (String name) {this.name=name;}
    public void   setEmail(String email){this.email=email;}
}

Edit 2

Thanks to @vladwoguer I found the logs, now I know that I am having issues with the class Json, the strange thing is that Netbeans autocomplete the function names, and doesn't show any error in the editor.

25-May-2019 01:11:57.354 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [Login Servlet] in context with path [/cactusstore-1] threw exception [Servlet execution threw an exception] with root cause
    java.lang.ClassNotFoundException: javax.json.Json
        at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1363)
        at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1186)
        at com.cactusmania.ui.Login.processRequest(Login.java:66)
        at com.cactusmania.ui.Login.doPost(Login.java:93)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1839)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:834)

If I comment out all the Json includes, and its use, and leave just:

System.out.println("YOUR EMAIL: "+req.getParameter("email"));

I obtain YOUR EMAIL: null in catalina.out.

Thanks again for your time and patience with me.

Copyright Notice:Content Author:「onlycparra」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56301890/how-to-send-and-receive-json-data-betweeen-javascript-and-servlet

Answers
vladwoguer 2019-05-25T20:35:57

The first problem I see is the exception: java.lang.ClassNotFoundException: javax.json.Json\nYou need to include it on the classpath.\nInclude the javax.json jar you are using in the YOUR_PROJECT/web/WEB-INF/lib folder in my case I used javax.json-1.0.jar.\n\nYOUR_PROJECT\n|\n|__web\n |\n |__WEB-INF\n |\n |__lib\n | javax.json-1.0.jar\n\n\nThis way when you export the war file and deploy it on tomcat, the jar wil be available on the classpath.\n\nThe second problem is that you are passing a JSON to the server and trying to get parameters with req.getParameter but what you really need is to parse the json and get the values like this:\n\n StringBuilder sb = new StringBuilder();\n BufferedReader br = req.getReader();\n String str = null;\n while ((str = br.readLine()) != null) {\n sb.append(str);\n }\n\n String json = sb.toString();\n\n\n JsonReader jsonReader = Json.createReader(new StringReader(json));\n JsonObject jsonObject = jsonReader.readObject();\n jsonReader.close();\n\n // an object with three fields.\n User u = new User(jsonObject.getString(\"email\"), \"10010099\", jsonObject.getString(\"pass\"));\n\n\nThe complete code:\n\npublic class Login extends HttpServlet {\n\n @Override\n protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {\n res.setContentType(\"application/json;charset=UTF-8\");\n try (PrintWriter out = res.getWriter()) {\n\n StringBuilder sb = new StringBuilder();\n BufferedReader br = req.getReader();\n String str = null;\n while ((str = br.readLine()) != null) {\n sb.append(str);\n }\n\n String json = sb.toString();\n\n\n JsonReader jsonReader = Json.createReader(new StringReader(json));\n JsonObject jsonObject = jsonReader.readObject();\n jsonReader.close();\n\n // an object with three fields.\n User u = new User(jsonObject.getString(\"email\"), \"10010099\", jsonObject.getString(\"pass\"));\n\n // construct json answer.\n // based on https://www.youtube.com/watch?v=BPMVC999HTs\n JsonObject root;\n JsonObjectBuilder rootBuilder = Json.createObjectBuilder();\n JsonObjectBuilder userBuilder = Json.createObjectBuilder();\n userBuilder.add(\"name\", u.getName()).add(\"email\", u.getEmail()).add(\"sid\", u.getSId());\n\n root = rootBuilder.add(\"login\", userBuilder).build();\n // write response to out\n out.println(root);\n out.flush();\n out.close();\n }\n }\n}\n",


More about “How to send and receive json data betweeen javascript and servlet?” related questions

How to send and receive json data betweeen javascript and servlet?

The Problem I cannot get to work the communication between a client with html/javascript sending the data of a form as json to a servlet, and then, the servlet replaying json back. I don't exactly...

Show Detail

Send Map to servlet with Ajax JSON

I'm building a Tomcat project, but I need to send a JavaScript Map to the Servlet. I tried to do this with JSON and Ajax. With a simple array I don't have any problems. But when I send a map on the

Show Detail

How to send a javascript array to the Servlet

I have an application where i am getting some values in the console in the form of a javascript array.now i want to send the values to the servlet.My javascript array look like this .. 0.Java 1.Pe...

Show Detail

Sending a json object using ajax to a servlet and receiving a response json object

I'm trying to send a json object using ajax to a servlet. The object is to be changed and sent back to the client. This is the code I used to send the json object from client to server. function

Show Detail

Unable to send Json data from Ajax to Servlet

I'm trying to send JSON data from a JavaScript function using Ajax to a Servlet. Client side: function addObject() { var data = { aa: &quot;aa&quot;, bb: &quot;bb&quot; } ...

Show Detail

How to send JSON from android to Servlet

I get the JSON of User Info from Facebook on Android. And then send the JSON to my servlet (the platform is GAE). My question is how to send it properly. Since the JSON could be very long. So far...

Show Detail

How to send a JSON object to a servlet

I want to send some data from my computer to a tomcat server which runs some servlets. And I also want to recieve the JSON from server. Can someone tell me is there a good framework or library to m...

Show Detail

unable to receive json to servlet post method

I was trying to send json data to my serlvlet. But when I try to receive that I got null. Below is my code. Where am I wrong? I don't understand. index.jsp &lt;%@ page language="java" contentType...

Show Detail

send json data from ajax and parse in servlet

Hi I am a newbie in servlet and trying to send object from javascript to servlet using ajax. javascript code looks like this: $.ajax({ url:'GetUserServlet', contentType: "application/j...

Show Detail

Sending and Receiving JSON data from a Servlet

How can I send JSON data to my Servlet's doPost() method and receive it back? I have a web service which produces and consumes JSON.

Show Detail