In my application, user confirms and a jsp page is loaded with confirmation details. I need to email that confirmation.jsp page in the same format.
I tried doing it as below:
In JSP page, surrounded the Body with <div id='content'>
and then through a load function, sent the contents of the page through request paramater:
function load(){
document.getElementById("emailbody").value=encodeURIComponent(document.getElementById('content').innerHTML);
}
But the issue is, the page format has changed and it is not in a HTML format (not at all in readable format).
In your case you should try sending mail on server side in a background thread so that your jsp rendering is not delayed. There are useful server side temlating engines like velocity which can help you achieve your tarhet html and would be easy to send then.
Related
I am very new to JAVA Servlets so pardon me if the question sounds silly. Basically, I have simple static HTML page having a form with input fields accepting values from a user. When a user enters values and click submit button values are sent to JAVA servlet where it does validation for values. If validation is failed I want servlets to send the old values which are correctly entered in addition to an error message for the invalid field and this will be displayed in static HTML page. How can I accomplish this with static HTML page and Java servlet?
I understand and totally agree that JSP would make my life easier in such case. However, if I have to use only HTML static page and JAVA servlet what are the options available?
You can include Javascript in the static web page that is called by the submit button onclick event and makes an AJAX call to the servlet. The servlet should respond with JSON or XML containing the validation results/error message. The form fields and/or error message text can be updated in the response handler Javascript function.
There are several examples on StackOverflow including this one. Scroll down to "Ajaxifying an existing form".
How can I effectively handle MaxUploadSizeExceededException in an ajax based file uploading operation.
I have an ajax based file upload functionality. I need to handle the MaxUploadSizeExceededException when user upload a file whose size exceeds the maximum allowed. I got the solution from here, where user will be directed to a error page, when file size exceeds. Since I am using ajax request to upload file, I want to show a javascript alert in the browser when file size exceeds, instead of redirecting to some error page.
How can I do this ?
A possible solution would be to completely follow the solution in your linked answer, where, on exception you would redirect to an error.jsp, which would in fact return JSON, so as simple as
error.jsp
<%# page contentType="application/json;charset=UTF-8" language="java" %>
{"errors":"${errors}"}
in which case the success part of your ajax call would be
success : function(json) {
alert(json.errors);
}
I don't know in Ajax, since you asked to show using javascript ,You can use ActiveXObject if you are using browsers that doesn't support HTML 5. If you are using modern browsers, you can use File APIs like below,
$('#fileId').bind('change', function() {
//The below code will get the size of the uploaded file.
alert(this.files[0].size);
});
You will get the file size in bytes, you can divide the file size by 1024 for getting in kb.
Can I send an entire HTML page with an AJAX response? If so, how to render that HTML page and what are the pros and cons doing that. The reason why I am asking this question is I found out that if we use response.sendRedirect("index.html") as a reply to an AJAX request in servlet we get the indx.html as AJAX response XML.
Your question doesn't make much sense and I can't quite tell what you're asking - the response to an ajax request will be whatever the server sends back. It could be plain text, XML, HTML, a fragment of an HTML/XML document etc. What you can do with depends on your script. If you're using a library like jQuery, what happens on the client side and what you can do with the response can also depend on how the library interprets the response (Is it a script? It it HTML/XML or JSON?).
if we use response.sendRedirect("index.html") as a reply to ajax request in servlet we get the indx.html as ajax response xml. Can some one pls explain this
An ajax request will behave much like a 'regular' HTTP request. So when you send back a redirect from your server (HTTPServletResponse#sendRedirect), the browser follows the redirect just like it would for any other request. If your ajax request was to a resource that required HTTP BASIC authentication, you'd see a prompt to login, just like you would if you visited the URL directly in a new browser window.
If you want to send HTML as a response, because you want to update divs, tables or other elements, but still want to use the same css or javascript files then it can make sense.
What you can do is to just send it as plain/text back to the javascript function, it can then take that and put it into the inner html element that you want to replace, but, don't do this if you want to replace the entire page, then doing what you want is pointless.
When you make the http request for your ajax call, it has its own response stream, and so when you redirect you are just telling the browser to have that http request go to index.html, as #no.good.at.coding mentioned.
If I get your question, you just want to know whether you could return whole entire HTML with AJAX and know the pro and cons.
The short answer to your question is yes, you could return the entire HTML page with your AJAX response as AJAX is just an http request to the server.
Why would you want to get the entire HTML? That's confusing to me and that is the part that I am not clear about. If you want to want to render the entire HTML (including tags like html, body, etc?), you might as well open it as a new page instead of calling it via Ajax.
If you are saying that you only want to get fragments of HTML to populate a placeholder in your page via AJAX then this is an acceptable practice. jQuery even provides load() function (http://api.jquery.com/load/) to make that task easy for you to use (check the section Loading Page Fragments).
Using this method, you could populate the placeholder using the HTML Fragments that is dictated by your server logic (i.e when the login fails or succeed) including the one via server redirect in your question.
so i am using java servlets to response to a request from a jsp page. and i want to change the html components name on that jsp page, like i change the buttons value or hide a label.i am wondering if there is any way to access jsp page's HTML components like button, text, ... in a servlet ?
i want to return the response in the same page that i have got the requests from. can i just simply write button1.name = "john" or text1.value = "ross geller" ?
Short answer is "no", longer answer is:
Firstly, you have to understand that HTTP and servlets is not an event-driven GUI like a desktop client, it's a lifecycle oriented, request/response paradigm. What this means is that the client (browser) makes a request for a page. The server (servlet) then responds with the HTML for that page. Once the servlet has sent the HTML to the browser, there is nothing that can be done on the server to change it, unless the browser makes a new request.
In this very basic paradigm, the lifecycle might look something like this:
A request is made by posting a form (browser) -> request is received (servlet) -> servlet does some processing based on request parameters -> HTML is generated (either by the servlet or by forwarding to a JSP page) -> HTML is sent back to the browser -> browser renders the page from the HTML
This is a very basic example, there are many variations on this based on which framework you use but they all boil down to something along these lines.
So, in your case, you have a page with, presumably, a form on it that has a button. You want to post that form and then return the same page but with some other label on the button. In the lifecycle abovem you would extract the parameters posted on the form from the request (paramters=all fields on the form). Then, in the HTML generation, you would use those request parameter values when building the HTML. I would advice you to search the web for some tutorials on servlet technology and look at some examples you might find and this will become clearer.
This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 7 years ago.
I currently have to generate an image that displays the text of a string, i need to make this image on a Servlet and then somehow pass the image to a JSP page so that it can display it. I'm trying to avoid saving the image, and instead somehow stream the image to the JSP.
I haven't found a way of generating the image since i started with finding how to pass an image from the Servlet to the JSP adn got stuck.
EDIT:
The jsp page is already made and isn't created by the servlet, i have to pass the image into an already existing jsp
Any help is appreciated.
You need to write the image as a byte array to the response's output stream. Something like this:
byte[] imageBytes = getImageAsBytes();
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(imageBytes);
Then in you JSP you just use a standard img element:
<img src="url to your servlet">
You can't1 return both in the same response, since you're returning different types (an HTML page of type text/html and an image of type image/jpeg, say).
For this sort of thing, I will generate the image during the initial servlet request (for the containing HTML page). I store it in a cache in my servlet, and write the HTML page with the image tag containing a URL to that image with the handle.
e.g. the browser asks for http://whatever/page
The servlet generates the image, and writes an HTML tag in the page like
<img src="http://whatever/image/unique_handle_to_image">
The browser will render the HTML page, and as part of that issue a new request to my servlet with the handle for the image.
e.g. the browser now asks for http://whatever/image/unique_handle_to_image
I then return the image as content type image/jpeg or similar.
So you have two requests going on. One for the page, in which you render the image and store it temporarily, and the second in which you return the image. You have to remember to clear the image cache, but that's all straightforward. I wouldn't worry about storing lots of images, since the two requests from the browser usually (!) come in quick succession.
I guess it's possible to use a data uri provided your browser supports it, and create something like
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
Note there are a number of caveats surrounding these. See the linked page.
I would do something along this lines to achieve this:
On the JSP page you put a link to an image:
<img src="servlet/path?word=value">the rest</img>
This link points to your servlet, it generates image using request parameters, you do not need to save it, just put it right into response's output stream. You have to remember to disable browser caching for this servlet.
JSP page is displayed first, next all the images are requested, it should work just fine.
Of course, you should not put the text to display in a parameter like this, you should propably encipher it somehow or store it in a HTTP session.
Hope this helps.
If I understand your problem correctly, the sequence of events will be:
You generate an HTML page;
That HTML page is sent to the client; and
The client's browser reads the image URL and requests it as a separate request.
So, you can't generate the image and pass it to the JSP. You can however generate a URL to get the image and put that in the JSP. That's easy enough to pass by the servlet putting it on the HttpServletRequest object (request scope in JSP). For example, generate:
<a href="http://myhost.com/image_servlet?id=1234"/>
You don't really say what that text is or what information is required to generate the image. If you can't encapsulate that in a GET URL, you may need to add extra information and put it in the HttpSession so it can be retrieved on the next get image request.
...
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length); // imageBytes - image in bytes
response.getOutputStream().write(imageBytes);//
outStream.flush();
outStream.close();