What is the response received by IE for a duplicate post? - asp.net

If you visit an aspx web form, and click the submit button causing a POST to the server, then click submit again causing a second POST before receiving a response from the first POST, what happens in terms of the response? Does the server process both requests simultaneously or serially? Does the server send both responses? Does the browser ignore one of the responses? This may be self explanatory after an answer to the previous questions, but if I were to call Response.Clear(); Response.End(); for the second request, what would happen on the browser end?

If there are no special means at the server side to handle multiple POSTs, the server will handle both requests independently. Whether or not the processing is concurrent - it depends:
if your first POST causes the whole page to reload then it is impossible to trigger the second POST before the page is processed at the server side (because your second click is made from the page which is already at the client side)
if your first POST causes an AJAX POST to the server and the processing takes some time at the server then it is possible that you end up with two POSTS from the same page processed concurrently at the server side
The server always sends responses and browsers do not ignore them. It is your code, at the server side or at the client side, to prevent such unintended multiple POSTs, for example by 302ing the response to another location which doesn't allow the user to rePOST the form.
Specifically, if you just clear the response (send an empty content) and the content type is text/html then the browser will render an empty page.

I would say just about any of those things could happen, depending on the exact timing.
I believe calling Response.Clear(); Response.End(); on the second request would cause an empty response which the browser would receive, possibly after receiving the results of the first request.

Related

URL not changed using servlet [duplicate]

What is the conceptual difference between forward() and sendRedirect()?
In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location header containing the new URL to which the client has to send a brand new GET request. So basically:
Client sends a HTTP request to some.jsp.
Server sends a HTTP response back with Location: other.jsp header
Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
Server sends a HTTP response back with content of other.jsp.
You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.
Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.
Client sends a HTTP request to some.jsp.
Server sends a HTTP response back with content of other.jsp.
However, as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp will be available in other.jsp. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp, hereby throwing away the original request on some.jsp including all of its attribtues.
The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().
You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
When you submit a form, you normally want to use POST:
<form action="login" method="post">
This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).
If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.
If a POST is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
request.setAttribute("error", "Unknown login, please try again."); // Set error.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}
A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET pattern.
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
doGet and doPost in Servlets
How perform validation and display error message in same form in JSP?
HttpServletResponse sendRedirect permanent
requestDispatcher - forward() method
When we use the forward method, the request is transferred to another resource within the same server for further processing.
In the case of forward, the web container handles all processing internally and the client or browser is not involved.
When forward is called on the requestDispatcherobject, we pass the request and response objects, so our old request object is present on the new resource which is going to process our request.
Visually, we are not able to see the forwarded address, it is transparent.
Using the forward() method is faster than sendRedirect.
When we redirect using forward, and we want to use the same data in a new resource, we can use request.setAttribute() as we have a request object available.
SendRedirect
In case of sendRedirect, the request is transferred to another resource, to a different domain, or to a
different server for further processing.
When you use sendRedirect, the container transfers the request to the client or browser, so the URL given inside the sendRedirect method is visible as a new request to the client.
In case of sendRedirect call, the old request and response objects are lost because it’s treated as new request by the browser.
In the address bar, we are able to see the new redirected address. It’s not transparent.
sendRedirect is slower because one extra round trip is required, because a completely new request is created and the old request object is lost. Two browser request are required.
But in sendRedirect, if we want to use the same data for a new resource we have to store the data in session or pass along with the URL.
Which one is good?
Its depends upon the scenario for which method is more useful.
If you want control is transfer to new server or context, and it is treated as completely new task, then we go for sendRedirect.
Generally, a forward should be used if the operation can be safely repeated upon a browser reload of the web page and will not affect the result.
Source
The RequestDispatcher interface allows you to do a server side forward/include whereas sendRedirect() does a client side redirect. In a client side redirect, the server will send back an HTTP status code of 302 (temporary redirect) which causes the web browser to issue a brand new HTTP GET request for the content at the redirected location. In contrast, when using the RequestDispatcher interface, the include/forward to the new resource is handled entirely on the server side.
The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens
at server end and not visible to client, but in case of
sendRedirect(), redirection happens at client end and it's visible to
client.
Either of these methods may be "better", i.e. more suitable, depending on what you want to do.
A server-side redirect is faster insofar as you get the data from a different page without making a round trip to the browser. But the URL seen in the browser is still the original address, so you're creating a little inconsistency there.
A client-side redirect is more versatile insofar as it can send you to a completely different server, or change the protocol (e.g. from HTTP to HTTPS), or both. And the browser is aware of the new URL. But it takes an extra back-and-forth between server and client.
SendRedirect() will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.
RquestDispatcher is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect() method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.
Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.
For example in the payment application
we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.
For other scenarios, forward is efficient to use since as it is faster than sendRedirect
Request Dispatcher is an Interface which is used to dispatch the request or response from web resource to the another web resource. It contains mainly two methods.
request.forward(req,res): This method is used forward the request from one web resource to another resource. i.e from one servlet to another servlet or from one web application to another web appliacation.
response.include(req,res): This method is used include the response of one servlet to another servlet
NOTE: BY using Request Dispatcher we can forward or include the request or responses with in the same server.
request.sendRedirect(): BY using this we can forward or include the request or responses across the different servers. In this the client gets a intimation while redirecting the page but in the above process the client will not get intimation
Simply difference between Forward(ServletRequest request, ServletResponse response) and sendRedirect(String url) is
forward():
The forward() method is executed in the server side.
The request is transfer to other resource within same server.
It does not depend on the client’s request protocol since the forward () method is provided by the servlet container.
The request is shared by the target resource.
Only one call is consumed in this method.
It can be used within server.
We cannot see forwarded message, it is transparent.
The forward() method is faster than sendRedirect() method.
It is declared in RequestDispatcher interface.
sendRedirect():
The sendRedirect() method is executed in the client side.
The request is transfer to other resource to different server.
The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
New request is created for the destination resource.
Two request and response calls are consumed.
It can be used within and outside the server.
We can see redirected address, it is not transparent.
The sendRedirect() method is slower because when new request is created old request object is lost.
It is declared in HttpServletResponse.

How server knows whether the request is Synchronous or Asynchronous?

When i make an ajax call to server the full page is not postback, only few amount of data goes to the server and return a response page.
But i am wondering about processing. How the Server or server code knows whether the request in normal call or Ajax call.
I request to experts, please clear my doubt.
Thanks in advance.
How the Server or server code knows whether the request in Normal call or Ajax call.
The server knows this if your javascript code marks the HTTP packet as such. E.g. in jQuery the HTTP header sent to the server has an X-Requested-With set and ASP.NET uses this to distinguish if HTTP packets are ajax calls or not.
To know more about HTTP packets you can inspect the ones sent either in a packet sniffer such as Fiddler or in a browser with dev. tools that monitors traffic. In the latter case you can see this in e.g. Chrome dev tools by doing the following:
Open up Chrome Developer Tools, Ctrl+Alt+I (or Cmd+Alt+I in Mac).
Select the Network tab (you may have to refresh the page to enable network monitoring)
Perform the Ajax call, the HTTP request made should show up in the list at the bottom.
Select the relevant packet, you should now see "Headers", "Preview", "Response", "Cookies" and "Timing" tabs for the selected packet.
Select the "Headers" tab
You may have to expand the Request Headers part. Among the headers should be X-Requested-With: XMLHttpRequest
Here is a screenshot of the tool looking at packages as I was editing this answer:
Note that ajax calls don't necessarily have to be asynchronous as they can be synchronous (blocking the javascript until response is loaded) as well. Synchronous calls are necessary sometimes, e.g. popup blockers don't allow you to open a browser window inside an asynchronous ajax callback.
How the Server or server code knows whether the request in Normal call or Ajax call
It doesn't. There is nothing about an HTTP request sent by Ajax that is any different from any other HTTP request.
The code that makes the request can do something to make it recognisable (e.g. by adding a query string, by changing the Accept header to something more suitable for the context (such as Accept: application/json) or by adding additional HTTP headers (some libraries add X-Requested-With: XMLHttpRequest).
None of those are guarantees as someone could always make an HTTP request manually. They are fine for determining which view to return within your own application, but not if you are trying to implement any kind of security.
AJAX calls performs with instance of XmlHttpRequest prototype. 3rd argument of its .open() method is async:bool. So
xhr.open("GET", "http://example.com", true)
is async and
xhr.open("GET", "http://example.com") is sync.
jQuery get(), post() and ajax() is async by default and you need to pass async param to make it synchronous. So answer to your question: YOU tell the browser what request you want.

What's the difference between a "GET" request and a "page refresh"?

Is there any difference between doing a "GET" request (type URL and Enter) compared to simply refreshing (CtrlR) the page?
No, it is not simply a get request, because on a page that you've POSTed to (from a separate form), the browser will confirm with you that you want to refresh the page because it is a POST request.
As for your question, you'll need to provide specifics for debugging purposes.
It is simply telling the browser to repeat the page load, which implies repeating the GET or POST request. Some browsers will inform the server that 304 (not-modified) is an acceptable response, and the server can reply with a 304 HTTP response to inform the browser that it's cached contents are valid
Most browsers ignore the Expires header if we do a "page refresh", yet respect it if we do a "url visit".
However, different browsers have their own way of differentiating "refresh" and "url visit", the only way to be sure is to manually test each one of them.

How to check if PUT can be performed before sending request body?

Note: we are using lib_neon on client side and Tomcat and servlet api on server side.
The problem is following: when client wants to put some content, it performs a PUT request with an "Expect: 100-continue" header, Tomcat handles it by simply returning status 100 Continue and after that client starts to send the remaining part of request, and it gets processed by our custom Filters and often it doesn't pass (for instance user is not authorized, or tries to put too large file, exceeding users limit, or something else). Filter sends an error response immidetetly, but client reads the response only when the full request body is commited.
It seems that it is impossible to manually send something instead of 100 Continue status, when some check fails, and this behavior is hardcoded into tomcat, is there any other way not to upload request body, when it is impossible?
You need a servlet container with a more sane 100-continue handling (I believe jetty qualifies).
I can't believe this clarification still isn't part of the servlet spec; I believe I asked for it something like 7 years ago.

Iframe keep-alive function - what is needed to reset the session timeout?

I have a hidden iframe that refreshes every now and then, in order to keep the ASP.NET session up and running, for as long as the user is online.
However, I have been getting reports of users experiencing session timeouts, so now I am in doubt of what is needed to reset the session timer.
The hidden iframe's content page (simple html page) refreshes itself at a certain interval, which is significantly less than the session timeout.
My question is: Is it enough (for the session timer to reset) to let the page refresh itself, even when the server responds with a HTTP/1.x 304 Not Modified?
Is it simply the GET request itself that tells the webserver to reset the session timer?
Or do I need to make sure to actually fetch the page and receive a HTTP/1.x 200 OK response?
All you have to do to keep the session alive is send a request to a page from the current session. You can do this via iframes, or via ajax.
If you simply refresh the page in the IFrame, the response may be a cached one - thus the 304. You have to send a fresh request every time -
var url = "http://domain.com/defibrillator.aspx?" + (new Date()).getTime();
E.g.
http://domain.com/defibrillator.aspx?1556467987987
http://domain.com/defibrillator.aspx?5448796497878
http://domain.com/defibrillator.aspx?4123165487987
....
EDIT 1
Or you can use the Refresh HTTP header attribute.
EDIT 1.1
If you are using the codeproject article mentioned above, then try to model it using AJAX instead of iframes - it would save you a few bytes of extra iframe markup.
EDIT 2 - About HTTP 304 Not Modified
If the client has performed a
conditional GET request and access is
allowed, but the document has not been
modified, the server SHOULD respond
with this status code. The 304
response MUST NOT contain a
message-body, and thus is always
terminated by the first empty line
after the header fields.
This means that the request hasn't reached the ASP.NET pipeline, and has directly been served by IIS itself. ASP.NET environment doesn't know that a request has been made. So, it won't perform the session renewal.

Resources