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

onlycparra :

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.

vladwoguer :

The first problem I see is the exception: java.lang.ClassNotFoundException: javax.json.Json You need to include it on the classpath. Include 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.

YOUR_PROJECT
|
|__web
   |
   |__WEB-INF
      |
      |__lib
         |  javax.json-1.0.jar

This way when you export the war file and deploy it on tomcat, the jar wil be available on the classpath.

The 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:

 StringBuilder sb = new StringBuilder();
 BufferedReader br = req.getReader();
 String str = null;
 while ((str = br.readLine()) != null) {
     sb.append(str);
 }

 String json = sb.toString();


 JsonReader jsonReader = Json.createReader(new StringReader(json));
 JsonObject jsonObject = jsonReader.readObject();
 jsonReader.close();

 // an object with three fields.
 User u = new User(jsonObject.getString("email"), "10010099", jsonObject.getString("pass"));

The complete code:

public class Login extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("application/json;charset=UTF-8");
        try (PrintWriter out = res.getWriter()) {

            StringBuilder sb = new StringBuilder();
            BufferedReader br = req.getReader();
            String str = null;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }

            String json = sb.toString();


            JsonReader jsonReader = Json.createReader(new StringReader(json));
            JsonObject jsonObject = jsonReader.readObject();
            jsonReader.close();

            // an object with three fields.
            User u = new User(jsonObject.getString("email"), "10010099", jsonObject.getString("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();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156535&siteId=1