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":"a@b.c","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.