How to pass an InputStream from a jsp to a servlet - java

I have to print on a jsp page some images that i get in the form of InputStream.
First i have servlet that passes a variable containing an InputStream to a jsp page, this way:
request.setAttribute("Image", InputStream);
request.getRequestDispatcher(pagename).include(request, response);
In my jsp page i have this to get that InputStream:
${requestScope.VariableContainingInputStream}
To turn that InputStream into an image i should use a servlet this way:
<img src="ServletName">
How can i pass that InputStream to that servlet?

How can i pass that InputStream to that servlet?
You wouldn't. Your JSP would create a temporary (or permanent) file and would write the contents of the InputStream to it. You'd then provide an endpoint that would serve up the content of that file.
You would then provide the URL to that endpoint in your JSP's <img> element.

If you get it as an InputStream, I assume the image is generated dynamically or generally speaking that you have something that gives it to you depending of a number of parameters.
You should think about how a normal (or stupid ...) browser will work :
the user clicks on a link, a submit button or pass an url in adress bar
the browser generate the corresponding request and sends it to the server
the server generate a (generally HTML) page containing links to images and sends it back to browser
the browser analyzes the page, and sends separate requests for the images
the server sends back the image one for each request
the browser display full page containing images
(you could replace images by css pages, js scrips, or any other resources)
So you should not get the input stream at the time of running your jsp to compose the HTML page but write in it <image source=/ImageServlet_url?params_for_current_image/>
Then when the browser will ask for the image, the image servlet will ask for the InputStream and put it directly in response body, with the correct type in the response headers.
This is by far the most robust way of solving your problem. If really it is not an option and the InputStream is only disponible at the moment of running the jsp, you must put in in a session attribute. Then when the ImageServlet will be called, it will look for it in the session and sends it. The problem is that an InputStream in not necessarily Serializable and it is unsafe to put non serializable items in session. So you should :
set a global Hash<String, InputStream> somewhere in your app
when trying to put the InputStream in session, actually put in in the hash (with a unique key) and store the key in session
when getting the InputStream from session, get the key from the session and fetch the InputStream from the hash ... and do not forget to remove it form the hash ...
I strongly advice you to stick to the first solution, not speaking or network errors or power outages between the request of the HTML page and the image ...

Related

Best way to serve image+html content to html page using servlet?

I'm trying to update a particular 'div' with profile pic and some html content without refreshing the whole page when the user successfully authenticated.
I
1) Stored the profile pic while user registration process to database( I could save it to a file system, but here my requirement is to store it in database blob)
2) Could able to retrieve image as a binary stream from database and display image alone(without any html content) to html page
I went through a couple of Answers in stackoverflow, they say we can't serve image+html content to the same webpage('div' in my case) from one servlet!
Help me to with how to serve image+html content to update just a 'div' of html page?
How about writing 2 servlets, one to take in the image and write it to the database and another one to get the image and pass it back in the response output stream which you can call from the webpage via an ajax call.
Get the output stream of the HttpServletResponse object passed into your servlet and use write method to pass back your image. I would encode your image to base 64 and wrap it with some html.
public void service(HttpServletRequest request, HttpServletResponse response) {
response.getWriter().println("html and base64 string");
response.getWriter().close();
}

what is in background of html submit form?

I'm trying to figure out what really happens when html submit form button is clicked.
I suppose it generates some kind of http request (similar to ajax get or post call) which has data in http body and is sent to address specified in action field.
1) Am I right?
2) I've seen many ways of processing forms with PHP or ASP on server side. Can I process it with Java REST Application using e.g. Jersey? Is submit form capable of hitting REST if I put right URL in action field?
Thank You.
By submitting the form in HTML you basically tell the browser to generate a normal HTTP request, usually POST or GET, for an URL defined in tag with form fields attached according to the specified method either appended to the URL or included in the request data.
There is nothing really special or different from a "normal" HTTP request, in fact you can manually "submit a form" by appending form keys and values to the URL in your browser and navigating to it in case of GET method.
Summarizing:
1) Yes, you are right.
2) From what I've just read (never used REST personally) a REST application is implemented by a servlet mechanism and uses HTTP protocol, so it should be possible to write a REST application for processing HTML forms if the form points to this application's URL.

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 to get textbox value in the same JSP without submiting it?

Actually i want to use the textbox value and set the session parameter in the same JSP page without submitting it or like using request or response object. This textbox value i want to use in the same JSP page for further use. How can i access the value of a text box in the same page?
You could either utilize the new HTML5 local storage (only supported in the more recent/modern browsers), or you could create a session cookie in JavaScript and store the value in there.
Note that none of those approaches will affect the server side HttpSession in any way. For that you simply can't go around sending a HTTP request containing the desired information, as that's the only way to send information from the client to server side. You could however consider using ajax to send the HTTP request asynchronously and fully transparently in the background.

redirect to a different url

I have one application where i have three jsp pages, from index.jsp , control goes to process.jsp and after execution control goes to result.jsp to display data. But i want that instead of displaying data in result.jsp, control will go to another url so that that receiver url will get the requested data. that is: my url is 100.20.3.45:8085/myproject/index.jsp then after processing data i want that result should go to a different url of my same network i.e. 100.20.3.46. How can I send the requested data to this different url?
Ex:
100.20.3.45:8085/myproject/index.jsp
goes to
100.20.3.45.8085/myproject/process.jsp
after processing control will go to 100.20.3.46.
How can I send this data to a different url? what is this mechanism called?
It's called "redirecting". It's to be achieved by HttpServletResponse#sendRedirect().
response.sendRedirect(url);
If you want to send additional data along, you'd need send it as request parameter(s) in a query string, but they will be visible in the URL in browser's address bar. If that isn't affordable, consider storing it in a shared datastore (database?) and then pass alone the unique key along.
Alternatively, you can also just let the <form> action URL point to that different host directly without the need for an intermediate JSP. As another alternative, you could also play for proxy yourself with help of for example URLConnection.
Unrelated to the concrete problem: having controller/business logic in JSPs is a bad practice. I suggest to take some time to learn about servlets.
Redirect to URL
window.location.href = "url"
Examples of use
window.location.href = "/process_payment";
var username = #json($username);
window.location.href = '/' + username;
window.location.href = '/{{ $username }}';

Categories