Issue
I facing problems when I'm trying to fetch data from Servlet. When I call the servlet by:
function urlFetchRequest(str, body = null, RequestType = 'GET'){
try
{
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open(RequestType, str, true); // /Test is url to Servlet!
asyncRequest.send(body);
}
catch(exception)
{
alert("Request failed");
}
}
I get back the information I need from the Servlet, and can use it by:
jsonRes = JSON.parse(asyncRequest.responseText)
which is work. My problem is when I need to pass data to the servlet. so I try to do it with fetch() since I have read that I can use JSON objects to the servlet (Again, I cannot use any javascript libraries such as jquery) and I can't use the data that the servlet returns. It getting "undefined".
The javascript scope that I using:
function newFetch(url, options){
fetch(url, options).then(async (res) => {
if(res.ok){
jsonRes = res.
if(theSurvey === null) {
surveyLength = Object.keys(jsonRes).length;
theSurvey = jsonRes;
}
}
});
}
I call it from here:
returnedObject.SurveyLoader = async () => {
//urlFetchRequest("/SurveyServlet");
//await SurveyResults();
newFetch("/SurveyServlet", {
method: "GET",
headers: headers,
})
}
My servlet is:
@WebServlet(name = "SurveyServlet", urlPatterns = {"/SurveyServlet"} )
public class SurveyServlet extends HttpServlet {
public static final Logger LOGGER = Logger.getLogger("SurveyServlet");
private BufferedReader m_reader;
private String m_line;
public String convertWithStream(Map<String, String> map) {
String mapAsString = map.keySet().stream()
.map(key -> '\"' + key + '\"' + ":" + '\"' + map.get(key) + '\"')
.collect(Collectors.joining(", ", "{", "}"));
return mapAsString;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> SurveyObj = new LinkedHashMap<>();
m_reader = new BufferedReader(new FileReader(getServletContext().getRealPath("/poll.txt")));
m_line = m_reader.readLine();
SurveyObj.put(Integer.toString(0), m_line);
int id = 1;
while((m_line = m_reader.readLine())!=null) {
SurveyObj.put(Integer.toString(id), m_line);
++id;
}
String str = convertWithStream(SurveyObj);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//request.setAttribute("ArraySize", id);
// getServletContext().getRequestDispatcher("ResultServlet").forward(request,response);
PrintWriter out = response.getWriter();
out.write(str);
out.flush();
out.close();
}
}
My question here is about the fetch method. I know it gets Objects from a REST API. how do I use it to pass and get data from the servlet? how do I use the data I send to the servlet? If it's not possible, how do I use XMLHttpRequest to pass data to the servlet? (no $ use)
Thanks.
Solution
It does not completely answer my question, but most of it: I succeed to find a way to send a JSON object to my ajax client.
I used this in my client side (the url is my servlet name, and the options contain only the headers (content type etc):
function newFetch(url, options){
fetch(url, options).then(res => res.json()
).then((resp) => {
jsonRes = resp;
if (theSurvey === null) {
surveyLength = Object.keys(jsonRes).length;
theSurvey = jsonRes;
SurveyResults();
}
});
}
And in the servlet, I used javax library to use JSON object methods, that way:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> SurveyObj = new LinkedHashMap<>();
m_reader = new BufferedReader(new FileReader(getServletContext().getRealPath("/poll.txt")));
m_line = m_reader.readLine();
SurveyObj.put(Integer.toString(0), m_line);
int id = 1;
while((m_line = m_reader.readLine())!=null) {
SurveyObj.put(Integer.toString(id), m_line);
++id;
}
JsonObjectBuilder builder = Json.createObjectBuilder();
SurveyObj.forEach(builder::add);
JsonObject obj = builder.build();
// String str = convertWithStream(SurveyObj);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try (OutputStream out = response.getOutputStream()) {
JsonWriter jsonW = Json.createWriter(out);
jsonW.write(obj);
jsonW.close();
}
}
I hope it will help someone in the future. anyway, I'm still facing the problem of sending JSON object to the servlet and access it via my request. If anyone can help - it will be perfect. if I'll find the answer, I will edit the post.
Thanks.
Edit: After lots of searching and tries, I find the best way, in my opinion, to pass data to the servlet: 1. Add to your servlet this annotation: @MultipartConfig 2. In your client-side, Use "FormData", and it will be possible to send it via fetch in the request body:
let formData = new FormData();
formData.append("size", surveyLength.toString());
newFetch('ServletResults', {
method: "POST",
//headers: headers,
body: formData
And because the annotation of @MultipartConfig, the servlet knows how to access parameter via "request.getParameter"
I hope this will help to someone in the future. Thanks, everyone.
Answered By - Eran
Answer Checked By - Mildred Charles (JavaFixing Admin)