I have developed an HTML page with an input field. Using javascript, I extract the input value, convert it into JSON format, and attempt to send it through ajax. Additionally, I have a JSP application where a Java method processes this JSON data to store it in a database. However, the challenge lies in receiving the ajax call in my JSP application and passing it on to the Java method. Can anyone offer guidance on how to achieve this?
Javascript:
alert("I am preparing to POST the following:\n\n" + dat);
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'JSON',
data: dat,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
`
JSP:
'<%@ page language="java" import="connection.JsonHandler" %>
<%
String json = request.getParameter("dat");;
JsonHandler gson = new JsonHandler();
gson.ReadJson(json);
%>
Java:
package connection;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import entidades.User;
import java.lang.reflect.Type;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonHandler {
public Gson CreateJson(String values) {
Gson gson = new GsonBuilder().create();
gson.toJson("Hello", System.out);
gson.toJson(123, System.out);
return gson;
}
public void ReadJson(String json){
Gson gson = new Gson();
Type type = User.class;
gson.fromJson(json,type);
}
}