Save as popup for itext generated PDF [duplicate] - java

I have created a zip file in my servlet. Now I would like to trigger that servlet using Ajax and prompt the download dialog to the user. I can trigger the servlet, but I don't know how to get the save dialog. How can I achieve this?

You can't "download a file using AJAX". AJAX is about downloading data from a server for JavaScript to process.
To let the user download the file either use a simple link to the file/servlet, or if you really, really need to use JavaScript, then assign the URL to document.location.href.
Also you need to make sure that the server (or in this case the servlet) sends the appropriate MIME type, in case of a ZIP file most likely application/zip.

You can't use Ajax for this. You basically want to let the enduser save the file content to the local disk file system, not to assign the file content to a JavaScript variable where it can't do anything with it. JavaScript has for obvious security reasons no facilities to programmatically trigger the Save As dialog whereby the file content is provided from an arbitrary JavaScript variable.
Just have a plain vanilla link point to the servlet URL and let the servlet set the HTTP Content-Disposition header to attachment. It's specifically this header which will force the browser to pop a Save As dialog. The underlying page will stay same and not get refreshed or so, achieving the same experience as with Ajax.
Basically:
download file
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
response.setHeader("Content-Type", getServletContext().getMimeType(fileName));
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
// ...
}
That could also be done in JavaScript as below without firing a whole Ajax call:
window.location = "fileservlet/somefilename.zip";
Alternatively, if you're actually using POST for this, then use a (hidden) synchronous POST form referring the servlet's URL and let JavaScript perform a form.submit() on it.
See also:
Simplest way to serve static data from outside the application server in a Java web application
Abstract template for a static resource servlet

function down() {
var url = "/Jad";
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
//alert("xmlhttp.status" + xmlhttp.status);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
var elemIF = document.createElement("iframe");
elemIF.src = url;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
}

Related

redirect not happening although location has the correct url

I am uploading few images with an upload functionality written in java. As soon as the upload is in progress there is a gif to show the progress bar. Now when there is the session timeout I am redirecting to the login page.
if (StringUtils.isNotBlank(request.getQueryString())) {
queryString = request.getServletPath() + "?" + request.getQueryString();
} else {
queryString = request.getServletPath();
}
LOGGER.debug("Query String:" + queryString);
if (!StringUtils.equalsIgnoreCase(StringUtils.substringAfterLast(queryString, ApplicationConstants.DOT),
ApplicationConstants.JSON)) {
request.getSession().setAttribute(ApplicationConstants.QUERY_STRING, queryString);
}
try {
LOGGER.error("In navigateToLandingPage. Redirecting to Failure View:" + this.getFailureView());
response.sendRedirect(request.getContextPath() + "/" + this.getFailureView());
// response.setHeader("Refresh", "5; URL=http://XXXX/login.htm");
} catch (IOException e) {
throw new BusinessException("Exception in redirecting", "-1", this.getClass().getCanonicalName(), e);
}
When I am analyzing the network in browser i can see the response with 302 status and also the location has the intended URL but some how the response in not getting processed and stuck at the progress bar screen.
If i manually refresh the stuck page i am directed on the login page i am trying to add
response.setHeader("Refresh", "5; URL=http://lXXXXX/login.htm"); below the redirect but no luck.
Can anyone please help me around with this.
There is a workaround where instead of sending 302 i am sending 901 which i am checking at js and directing to login which works fine but i intend to use redirect.
So, the request was fired asynchronously using JS instead of synchronously using web browser? In other words, you were trying to redirect an ajax request?
If you're sending a redirect as response to an ajax request, then XMLHttpRequest will by default just follow that redirect. I.e. it will re-send the ajax request to that URL. This is obviously not what you intented. You want a synchronous redirect, not an asynchronous one.
The canonical approach is to just instruct the ajax engine in some way that it needs to perform a window.location call on the given URL. If you're using JSON or XML as data format, then you can just add a special instruction which your ajax engine can then check on.
E.g. in case of JSON:
response.getWriter().printf("{redirect:\"%s\"}", url);
var response = fireAjaxRequestAndGetResponseAsJsonSomehow();
if (response.redirect) {
window.location = response.redirect;
return;
}
// Usual process continues here.

Search Variables in HTML from Java?

Whilst working on our coursework for Computer Science, we have had to change from Java to JavaScript in HTML due to a server in-capability. Therefore, I have spent all my research into Java and have a fully working computer program in Java but with this new problem, my whole project needs to be made into JavaScript (or better, HTML)... I have had a brief working with HTML & Dreamweaver so I know how the UI etc. but I need help making a Search Bar that has variables. Previously, it was coded as
(search bar here)
if search == example:
System.out.println("You have chosen example")
etc
but now we have had to convert everything to HTML and I have no clue on how to make the if statements in this new language...
Any help is welcomed!
In your case you need to consider Java Servlet technology.
You will need to have a servlet on the server (servlet-container), and an HTML page, with JavaScript code, that makes a GET request with parameters to this servlet.
Note, that you need to encode the search string, before passing it to the server.
This servlet receives request from the client (HTML page), does the search, and prints results to the output stream.
Your JavaScript code receives server response and modifies HTML page to show the search results.
To implement client/server interaction via asynchronous requests (AJAX) consider jQuery.
Here is an example, how to make a GET request to the server: https://api.jquery.com/jquery.get/
plain sample:
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
And there is an example, how to read GET request params in the servlet:
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
}

Django and Java Applet authorization failed

I'm building a Django App with allauth.
I have a page, with authentication required, where I put a Java applet. This applet do GET requests to other pages (of the same django project) which return Json objects.
The applet gets the CSRF token from the parent web page, using JSObject.
The problem is that I want to set ALL the pages with authentication control, but I cannot get the sessionid cookie from the parent web page of the applet, so it cannot do GET (and neither POST) to obtain (or save) data.
Maybe it is a simple way to obtain this, but I'm a newby, and I haven't found anything.
Ask freely if you need something.
Thank you.
EDIT:
Has I wrote downstairs, I found out that the sessionid cookie is marked as HTTPOnly, so the problem now is which is the most safe way to allow the applet to do POST and GET request.
For example it is possible to create a JS method in the page, which GET the data and pass it down to the applet?
Maybe in the same way I can do the POST?
EDIT:
I successfully get the data, using a jquery call from the page. The problem now is that the code throws an InvocationTargetException. I found out the position of the problem, but I don't know how to solve it.
Here is the Jquery code:
function getFloor() {
$.get(
"{% url ... %}",
function(data) {
var output = JSON.stringify(data);
document.mapGenerator.setFloor(output)
}
);}
And here there are the two functions of the applet.
The ** part is the origin of the problem.
public void setFloor(String input) {
Floor[] f = Floor.parse(input);
}
public static Floor[] parse(String input) {
**Gson gson = new Gson();**
Floor[] floors = gson.fromJson(input, Floor[].class);
return floors;
}
And HERE is the log that come out on my server, where you can see that the applet try to load the Gson's library from the server (instead from the applet)
"GET /buildings/generate/com/google/gson/Gson.class HTTP/1.1" 404 4126
Somebady can help me?
You can do something like this in your applet:
String cookies = JSObject.getWindow(this).eval("document.cookie").toString();
This will give you all the cookies for that page delimited by semicolons.

Redirect to servlet fails

I have a servlet named EditPhotos which, believe it or not, is used for editing the photos associated with a certain item on a web design I am developing. The URL path to edit a photo is [[SITEROOT]]/EditPhotos/[[ITEMNAME]].
When you go to this path (GET), the page loads fine. You can then click on a 'delete' link that POSTs to the same page, telling it to delete the photo. The servlet receives this delete command properly and successfully deletes the photo. It then sends a redirect back to the first page (GET).
For some reason, this redirect fails. I don't know how or why, but using the HTTPFox plugin for firefox, I see that the POST request receives 0 bytes in response and has the code NS_BINDING_ABORTED.
The code I am using to send the redirect, is the same code I have used throughout the website to send redirects:
response.sendRedirect(Constants.SITE_ROOT + "EditPhotos/" + itemURL);
I have checked the final URL that the redirect sends, and it is definitely correct, but the browser never receives the redirect. Why?
Read the server logs. Do you see IllegalStateException: response already committed with the sendRedirect() call in the trace?
If so, then that means that the redirect failed because the response headers are already been sent. Ensure that you aren't touching the HttpServletResponse at all before calling the sendRedirect(). A redirect namely exist of basically a Location response header with the new URL as value.
If not, then you're probably handling the request using JavaScript which in turn failed to handle the new location.
If neither is the case or you still cannot figure it, then we'd be interested in the smallest possible copy'n'pasteable code snippet which reproduces exactly this problem. Update then your question to include it.
Update as per the comments, the culprit is indeed in JavaScript. A redirect on a XMLHttpRequest POST isn't going to work. Are you using homegrown XMLHttpRequest functions or a library around it like as jQuery? If jQuery, please read this question carefully. It boils down to that you need to return a specific response and then let JS/jQuery do the new window.location itself.
Turns out that it was the JavaScript I was using to send the POST that was the problem.
I originally had this:
Delete
And everything got fixed when I changed it to this:
Delete
The deletePhoto function is:
function deletePhoto(photoID) {
doPost(document.URL, {'action':'delete', 'id':photoID});
}
function doPost(path, params) {
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", path);
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();
}

how read a remote file with GWT

I need to read a file located on a server but I see that in GWT is not possible use some java library.
what I have to do?
try requestBuilder!! this code can help?
RequestBuilder requestBuilder = new RequestBuilder( RequestBuilder.GET, "yourfile.txt" );
try {
requestBuilder.sendRequest( null, new RequestCallback(){
public void onError(Request request, Throwable exception) {
GWT.log( "failed file reading", exception );
}
public void onResponseReceived(Request request, Response response) {
String result=response.getText();
}} );
} catch (RequestException e) {
GWT.log( "failed file reading", e );
}
The Rule: JavaScript cannot read data from a URL that doesn’t have a host name and port that matches those of the page the JavaScript is running in.
In other words: If it is on a different site — you can’t read it directly with JS and therefore GWT, which is nothing more than Javascript once compiled.
It applies to data from XMLHttpRequest, frames, and anything else you care to name.
This may change in the future, but for now the rule stands.
With this in mind there are a couple of workarounds.
1) Call your server with RPC or whatever mechanism and have your server do the request and then send it back to the client. Here is a sample.
2) There are several hacks on allowing JavaScript to access cross-domain sites just do a google search on how to get this. Some browsers will flag this as being dangerous.
3) If you are using Firefox and Firefox only it looks like Firefox has the ability to do this, but you will need to enable this manually.
Simply write first a servlet that sends the file located on the server to the user.
Then when the user clicks on a button for instance you call the servlet with the proper parameter.
Here is an excerpt from our servlet implementation
response.reset();
response.setContentType("application/octet-stream");
response.setContentLength(contentLength);
response.setHeader("Content-disposition", "attachment;
filename=\"" + filename + "\"");
output = new
BufferedOutputStream(response.getOutputStream());
int data = input.read();
while (data != -1)
{
output.write(data);
data = input.read();
}
output.flush();

Categories

Resources