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

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();
}

Related

invoke jsp from java code and get output

I have a JSP page that show data in some formatted way. the browser can call spring showInfo.do and it is forward to that JSP.
i.e.
public showInfo(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("info.jsp");
dispatcher.forward(request,response);
}
The output of the JSP is html.
Now I want to save this JSP output manually from my java server side code (not in a servlet context), something like this:
void saveInfo() {
params.setParameter("info1", "data");
String responseStr = Invoke("info.jsp", params);
//save responseStr to disk
}
I want to be able to save the html page on disk from a service and make it look the same as a user can see it from a browser. So if the server is offline a user can double click on the saved html file and see in his browser the last info.
Any idea how this can be done?
Oups. The servlet specification requires the servlet container to be able to execute a JSP file. This is commonly done by converting the JSP to plain Java and the generating a servlet class file.
If you are outside of a servlet container you must:
* either fully implement a JSP execution environment, for example by using sources from a servlet container like Tomcat
* or rely on a servlet container to convert the JSP file to a .java or .class servlet and then use the Servlet interface methods on it
Alternatively, you could try to use a headless browser to capture the output of the application.

How to display a default image when image source is a servlet?

In my JSP/ Servlet setup, for displaying user profile images I am directing the img tag to get the image from servlet by specifying servlet URL in src tag and then returning image in response from servlet.
Sevlet does below things upon receiving an image request,
It gets the image from database in BLOB format
Prepares image from the byte[] and
returns the image in response object with appropriate headers.
My problem is since Signup page doesn't has image upload option so new users don't have their image in database i.e. so the BLOB is NULL. How can I display a default image for all such users ?
EDIT
Based on comments received I just wanted to note that. I am aware of the solutions where we set the default value either in database (while creating the user) or return the default image array when there is NULL in database. I am already using the later case. By this question I just wanted to discuss about any other possible solutions.
One option could be to return HTTP error 404 "Not found" when the user don't have an image. It seems quite logical to me, since there really is no image for the user.
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
Then in your HTML you can handle this case using the onerror Event to set the default image:
<img src="servletUrl" onerror="this.src='default.png'" width="150" height="150" />
In this way the servlet only sends user images and does not do any special logic if the user doesn't have one.

How to pass an InputStream from a jsp to a servlet

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 ...

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.

Downloading file using Spring Portlet MVC

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.

Categories