After the successfull attempt to upload a file the request is forwarded to his home page, the same page from where he uploaded the file. If the upload is sucessfull, before forwarding the request, an attribute is set which tells, “yes the file has been uploaded successfully!”.
The following code in the user home page is executed that aims to check if the user has to be told about the successfull upload attempt. If the user has once seen the success message in the form of alert box, the next time he should see the success message when he uploads another file successfully. But after the first attempt when I reload/refresh the page I again see the alert box telling the user of successfull upload attempt, even when I have removed the attribute from the request list.
Snippet that displays the success message to the user after a successfull file upload attempt
<script>
window.onload = function() {
<% message = (String)request.getAttribute("SuccessMessage");
AttemptToUploadFile = (Boolean)request.getAttribute("UploadAttempt");
request.removeAttribute("SuccessMessage"); // Remove the attribute so that alert box doesn't pop every time the page is refreshed
if(message != null) {%>
alert("File successfully uploaded !");
<% } %>
}
</script>
Why do I see alert box again and again even when I have removed the particular attribute?
You’ve somewhere a conceptual misunderstanding as to how HTTP works and the “server side” and “client side” concepts.
Request attributes are already trashed/garbaged whenever the HTTP response associated with the particular HTTP request has finished its job of sending the response body (in this paritular case, the JSP-generated HTML source code) to the client side.
Refreshing/reloading a page in the browser (and ignoring the browser’s warning that the data will be resent!) will cause the original HTTP request data to be resent to the server and hence the server will process the entire HTTP request once again and set the request attribute once again. Explicitly removing the attribute will not solve it and makes at its own no utter sense.
I’m not sure what’s the functional requirement is. Do you want to allow the enduser to resend the uploaded file once again? Why would you not display the message once again? Shouldn’t the enduser rather be warned that s/he is attempting to resend the file once again which is wrong in the first place? In that case, add an extra check in the
doPost()method wherein you validate the filename based on the already-stored files on the disk, or some map in the session scope, and let it ignore the request and throw some exception or show a different message.Your JSP code can then be simplified as:
(although I personally disagree the way of giving feedback by 90’s style alerts)