I need help. I have single html-file running on my webserver. Via Javascript I'm sending data to my Java-Servlet on the same server via xhttp-request.
On Java's servlet side I can send a message back to the xhttp-request via a PrintWriter like below:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
PrintWriter theMessenger = response.getWriter();
theMessenger.print("Response data");
}
That all works fine. But now I need to send a message to the requesting html-file without the use of the servlet-response.
Are there any possibilities for sending data (strings as usual) to the html-file gathering those messages via onmessage-handler for example?
I tried this, but the messange never reaches it target:
String targetURL = CSConfig.GetRootURL() + "/myRequestingPage.html";
URL objUrl = new URL(targetURL);
HttpURLConnection urlCon = (HttpURLConnection) objUrl.openConnection();
urlCon.setRequestMethod("POST");
urlCon.setDoOutput(true);
DataOutputStream dataWriter = new DataOutputStream(urlCon.getOutputStream());
dataWriter.writeBytes(messageContent);
dataWriter.flush();
dataWriter.close();
Related
public String Home(HttpServletRequest request,
HttpServletResponse response, HttpSession session) {
String refer = request.getHeader("Referer");
request.setAttribute("refer", refer);
return "home/visit/editVisit";
}
public String Home2(HttpServletRequest request,
HttpServletResponse response, HttpSession session) {
String refer2 = request.getParameter("refer");
return "home/visit/addVisit";
}
In the first step, I get the function from one Controller to another Controller and since then the request changes in URL.
The new Controller page has several different functions.
I can catch the change there to know from which page I came by the line:
String refer = request.getHeader ("Refer");
But as I continue (by the buttons ...) to the next pages of the project. I don't have access to refer variable.
How can I be constantly available to a variable that would please and not only refer to a specific JSP?
I need quick help,
Thanks for every reply
I am trying to do some frontend logging using log4js and sending the logs using the AjaxAppender to the server backend using Java. This is the frontend code that I use to initialize the logger, I've made sure the logger works with a DefaultLogger, and switched to AjaxAppender.
var log = log4javascript.getLogger();
var ajaxAppender = new log4javascript.AjaxAppender("logger");
ajaxAppender.setTimed(true);
ajaxAppender.setTimerInterval(10000); // send every 10 seconds (unit is milliseconds)
log.addAppender(ajaxAppender);
//convert to JSON format
jsonLayout = new log4javascript.JsonLayout(false, false); //readable, combineMessages
ajaxAppender.setLayout(jsonLayout);
ajaxAppender.addHeader("Content-Type", "application/json");
log.info("Begin Session")
This is the backend code written in Java, which gets the logs sent from the frontend.
#RequestMapping(value = "/logger", method = RequestMethod.POST)
#ResponseBody
public String logger(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, IOException, SQLException {
System.out.println("Inside Logger");
System.out.println("Log:"+request);
return "Test successful:" + request;
}
However, I am getting the error XHR failed loading POST and the code doesn't seem to go inside the logger function ("Inside Logger" is not printed in terminal). I'm fairly new to working with Ajax and sending request between frontend and backend, is there a reason why the XMLHttpRequest is not going through?
Thanks!
404 means the service isn't reachable. Are you sure you've started the service and configged it properly?
I'm looking for a way to send a redirection with my servlet from my first page to a second page adding into the second page a script tag made inside this servlet.
For example:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Received a get request");
response.getWriter().append("<script>alert(\"I'm here!\")</script>");
response.sendRedirect("testRedirect.html");
}
This code doesn't work. How can I fix it?
Thanks!
response.sendRedirect writes the redirect header to the output stream. Headers must be sent before any output, this is why your code doesn't work.
Try swapping the two statements, redirecting first and then appending:
response.sendRedirect("testRedirect.html");
response.getWriter().append("<script>alert(\"I'm here!\")</script>");
Thank for your answers I solved with this code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("received a get message");
PrintWriter out = response.getWriter();
out.println("<script>alert(\"I'm here\");</script>");
request.getRequestDispatcher("testRedirect.html").include(request, response);
out.close();
}
You cannot send the content of the second page inside the redirection response. There are actually two requests.
The first request is handled by your servlet by sending the redirect. There should nothing else in this response.
The browser receives the redirect and does a second request to "testRedirect.html". If you want to include the script tag in the second response the right place to do it is the servlet or JSP which handles this second request.
You can send the user to the desired page by using javascript instead.
out.println("<script> alert(\"I'm here\"); window.location.replace(\"testRedirect.html\"); </script>");
I am using JS to obtain a variable and then make a POST call to a Servlet. I am not using Ajax explicitly.
$('#download').click(function (e) {
....
$.post('downloadServlet', {'var': variable});
//e.preventDefault();
});
The Servlet has code to read a file and, in theory, send it, but I do not get any response.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
....
response.setContentType("application/octet-stream");
response.setContentLength(...);
response.setHeader( "Content-Disposition", String.format("attachment; filename=%s", path.getFileName()));
try (OutputStream out = response.getOutputStream()) {
Files.copy(path, out);
out.flush();
}
System.out.println("Done");
My questions is Why is the file not sent/received? From a technical point, I am not sure I understand why it doesn't work, since I am not using Ajax. The POST method seems to execute as any normal submit form. I have read this but doesn't clarify. Any didactic explanation will be appreciated.
I have a REST service that retruns byte[]
I like to create an image (Ext.Img) which content is the service result
Service
#RequestMapping(value = "/retrieve_thumbnail", method = RequestMethod.GET)
public byte[] retrieveBDocumentThumbnail(#RequestParam String modelName,#RequestParam String modelVersion) throws BdocWebAccessException {
return service.retrieveBDocumentThumbnail(modelName, modelVersion);
}
Image
Ext.create("Ext.Img", {
src:'tablet/bDocument/retrieve_thumbnail?modelName=MODELE_INT_003_TYPES_DONNEES&modelVersion'
})
The service is invocked but I have this message in the javascript Console:
Resource interpreted as Image but transferred with MIME type text/plain: "http://localhost:8080/bdoci-tablet/tablet/bDocument/retrieve_thumbnail?modelName=MODELE_INT_003_TYPES_DONNEES&modelVersion".
I think that the problem is related to the format, How can I fix this?
The MIME type is an HTTP header that indicates what kind of file it is. In this case, it is sending text/plain. It should be indicating this is an image. I don't think your problem is on the client side, but the client is responding to an invalid response on the server side.
#RequestMapping(value = "/retrieve_thumbnail", method = RequestMethod.GET,
produces = MediaType.IMAGE_PNG_VALUE)