Downloading file using Spring Portlet MVC - java

I want to allow the user to save file using mvc portlet. In my code i am making an ajax call hence it has to be a resource response.
response.setContentType( "application/octet-stream" );
response.setProperty("Content-Disposition","attachment; filename=\""+fname+"\"");
response.setContentLength(b.length);
OutputStream po= response.getPortletOutputStream();
po.write(b,0,b.length);
po.flush();
po.close();
In ajax response when i do alert(resp), I am getting the whole content of my file in alert but still not getting any option for download.
Please help and thanks in advance ;)

Well, since you get the response, you need to allow the user to download it. You can for example use the HTML data: protocol and redirect the browser to smt. like
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAA...
for a PNG image.
Anyway, can't you use a normal request to a portlet? It's trivial then.

Related

Establish Connection First, Redirect User Second

I have an idea to make something pretty sweet but I'm not sure if it's possible. Here is an example of a very basic ajax function that I might use to establish a connection a server...
function getFakePage(userId)
{
var ajaxObject, path, params;
ajaxObject = getAjaxObject();
params = "?userId=" + userId
path = getInternalPath() + "someServlet" + params;
ajaxObject.open("GET", path, true);
ajaxObject.send();
// On ready state change stuff here
}
So let's say I have a URL like this...
https://localhost:8443/Instride/user/1/admin
And I wanted to use javascript to redirect the user to this this URL. Normally I would just do this...
window.location = "https://localhost:8443/Instride/user/1/admin";
But my idea is to create a javascript (no js frameworks please) function that could combine the ajax code with the window.location code. Basically what I would like to accomplish is to create a connection with the server via ajax, send a servlet on that server the url I would like the user to be redirected to, and then redirect the user to that URL. So that for however long it takes the user to connect to my server from wherever they are in the world they see a loading icon instead of a blank white page.
So to clarify exactly what I am trying to accomplish; I do not want to put window.location within the success of my ajax function (because that would be encompass two round trips), and I do not want to return a huge chunk of HTML for the requested resource and add it to the page. I want to establish a connection to the server with ajax, send a servlet the URL the user wants to go to, and then somehow override the ajax function to redirect that user. Is this possible?
And I know some of you might think this is stupid but it's not when you're talking about overseas users with slow dial up connections staring at white pages. If it's possible, I'd love to hear some insight. Thank you very much!
First, let me say that the best solution is finding what is causing the slowness and fixing it.
Now as to your question, yes you could do it. You could even shoehorn it onto an existing application. But it wouldn't be pretty. And it comes with it's own set of problems. But here are the steps:
Browser calls ajax cache service requesting "somepage.html"
Browser loads loading icon
Server creates somepage.html and caches it in a temporary cache, (ehcache or other library would be good, probably with file backing for the cache depending on size)
Server responds to ajax request with ID for cached page
Browser now redirects to "somepage.html?cacheId={cacheId}" where the id is from the ajax call.
Server uses a filter to see if any cache can be served up for the page instead of the actual page, thus speeding up the request.
Having said that, it would be better to just have the new page load quickly with a loading icon while it did any of the heavy lifting through ajax.
You can't do an AJAX request and a location change in one. If you want to do only one request you have to choose one of those methods. ie. return some data and replace content on your current page, or load a completely new page.
It doesn't make any sense to want to want to do both. What you could want is stateful URLs; where your URL matches the content displayed, even if that content comes from an AJAX request. In that case an easy solution is the use the # part of the URL which you can change freely (window.location.hash). Some modern browsers support changing the whole URL without causing the page to reload. I've used # with great success myself.

how do i know whether my html link is clicked or not from Servlet?

My Servlet response type is html and my response contains a hyperlink to another web site.So, now i want to capture the information about whether the user clicked the link or not? and also calculate the total clicks? i am using Tomcat 7 as a server.
Is this possible in setting response header (302 or 404)?...
Please Guide me to get out of this issue?
Yes, you can use a 302: instead of providing the link to the other website, you provide a link to your own servlet, do your accounting and then send back a redirection (301/302) http status with the other web-site URL in the response Location header.
This maybe a bit simplistic though, since the user will leave your original page (is this what you want ?) and search engines may not like this if your web app is public.
I think right now you are redirecting the request(link for another website) at client side.In this approach your server cannot get the information about the click.
What you can do create a servlet and call this servlet on click now this servlet is responsible to redirect the request to another website. Add an static integer counter and increment this when servlet call each time.
Use the method setStatus():-
setStatus(HttpServletResponse.SC_FOUND);
or
setStatus(HttpServletResponse.SC_NOT_FOUND);

Servlet 3.0 include html page

I'm trying to achieve the following behavior using the Servlet 3.0 API:
send an inital html page
send subsequent responses that update the page
This all works except the only way I could send the initial page without getting the response committed is by manually writing using the HttpResponse Writer...
I was wondering if there is a way of using something similar to RequestDispatcher#include with an html page without running into problems with the AsyncContext. Some things I tried until now and didn't work:
use AsyncContext#dispatch: as much as I read on the Internet, it is destined for sending the final response to the container in order to render it
use RequestDispatcher#forward: getting IllegalStateException due to trying to write more content in the OutputStream
use RequestDispatcher#include: if I initialize the AsyncContext before calling this method, request.isAsyncSupported returns true, after calling the method, it returns false. I read that it calls flushBuffer() and sets the commit flag to true on the response
Also, in the Servlet 3.0 spec there are some lines mentioning that dispatching from async servlet to normal servlet is possible but will commit the answer. I believe a static html page belongs to this category...
If you have any ideas of how an elegant include can be done without affecting the ability to still send streamed responses back to the client, please let me know.
Thanks
One solution (not the only one): if it's just a html page, then write the html page itself in html and do ajax calls to the serrvlet that needs to provide the updates.
use static elements on the page that store data and use requestdispatcher.
Or you could also just simply refresh the entire page with such an arrangement using response.setHeader("refresh", "5; URL=officer.html").
I really don't understand your need to send multiple requests without the response being committed to a servlet. are you trying to interact with a serving thread multiple times ?

GWT-Rpc how to return a file so that the browser pops up with a download dialog

Does anybody know if it is possible to have a GWT-rpc call cause a file download prompt to appear without having to do a second request to a separate servlet? I was thinking of having a method in the rpc servlet of return type void and then calling the response object directly to change the content type and cause the browser to open a download dialog.
Has anybody figured out a good way to achieve this without having a totally separate servlet?
It is not possible. HERE is the similar question I had while ago
I think you can try like this.On click of link you can do the following action.
Window.open("www.mydomain.com/downloadfile?fileId=something","_blank","");
Map the downloadfile url to some servlet and return the file.
But you cannot post data to server.You can add it in URL.In RPC call it is not possible send file.

jQuery Address - redirect after form submit

I use jQuery and AJAX to load content from links and forms into a content div. In addition I use the Address plugin to enable the back button and refresh. On the server side I use Java and Spring MVC.
Since I'm using jQuery Address and AJAX the only page that is directly loaded is "index.html". Everything else is loaded into a content div, and what page to load is specified in the hash, ie. "index.html#/users/add.html" will load "users/add.html".
Now, "users/add.html" contains a form for creating a new user. When the form is submitted and everything went OK, the controller redirects to "users/index.html". The problem is that jQuery Address doesn't know about the redirect, so the url will remain "index.html#/users/add.html". And this is a problem when you refresh the page and then get sent back to the form, instead of the index page.
Is there a way to fix this problem?
Thanks,
Stian
Take a look at the new Form Sample. It's very basic but will be probably usable.
http://www.asual.com/jquery/address/samples/form/
In your case you won't be able to use $('form').address() function because you will want to change the address after the server response comes back.
You can use a data.redirect property to detect potential response redirects:
How to manage a redirect request after a jQuery Ajax call
I realize my description of the problem wasn't the best, apologies for that.
I reformulated the problem in another question, got no answers but I found a solution myself. :)
AJAX - Get response URL after redirect
First I init my form like that :
$('FORM').submit(function () {
shareData = $(this).serializeArray();
$.address.value($(this).attr('action'));
})
after I have in my change method something like that :
$.address.change(function(event) {
if (event.path != '/' && event.parameters.layout_to_use != undefined) {
// if no json, load don't do a post request
shareData = _arrayToJson(shareData);;
$('#areatoreload')
.html('<span style="background-color:red;">loading...</span>')
.load('myscript.php', shareData, function() {});
}
return false;
});
And i manage my link in the same way. I hope it can help you. shareData is not a very good way, but i don't find something else for the moment. this code is not tested, I just extract some part of my own code.

Categories