The Communication Challenge
Struggling with establishing communication between a client using html/javascript to send form data as json to a servlet, and then receiving json back from the servlet. The process seems to have some errors that I am unable to pinpoint.
Here's how it should work:
- JavaScript retrieves data from a form, converts it to json, and sends it to the servlet.
- On the server side, the servlet reads the json, takes necessary action, generates another json response, and sends it back.
- Back on the client side, the json is received and used to draw dynamic html content. (Currently just logging it with
console.log()
)
The Client-Side Code
A piece of javascript code responsible for handling the form submission:
// Adding event listener to the form submit
document.querySelector('#login_form').addEventListener('submit',(e)=>{
e.preventDefault();
login_send(e.target);
});
// Function to handle form submission
function login_send(form){
console.log(form2json(form));
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("Response: "+data);
})
.catch((err) => console.error(err));
}
// Custom function to convert form data to json
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 Configuration
Defining the url mapping in the web.xml file to connect the servlet 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 Implementation
...
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()) {
User u = new User(
req.getParameter("email"),
"10010099",
req.getParameter("pass")
);
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();
out.println(root);
out.flush();
out.close();
}
}
}
An error occurs when trying to receive json response:
custom.js:23 SyntaxError: Unexpected end of JSON input
This issue suggests that the servlet might not be returning anything. As an attempt, modifying the res.json()
or res.text()
methods doesn't resolve the situation. Even changing out.println(root)
directly results in no output being received.
Your insights would be greatly appreciated! (With my limited experience in these languages, any guidance is valuable).
Edit 1
User Class Details
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;
}
// Getters and setters omitted for brevity
}
Edit 2
Thanks to @vladwoguer, logs were examined revealing issues related to the Json class. Surprisingly, Netbeans shows no error but autocomplete functions are also failing. Further exploration is ongoing!
Error Logs:
java.lang.ClassNotFoundException: javax.json.Json
...
System.out.println("YOUR EMAIL: "+req.getParameter("email"));
Result:
YOUR EMAIL: null
Grateful for your continued support and patience during this learning process.