I have written test Filter (javax.servlet.Filter) and started to debug. And I was surprised that one refresh of html page calls twice method doFilter().
Could anybody describe me why it happens ?
Thanks.
Perhaps your filter was called also for static elements (images, etc.). Check your filter path declaration in web.xml.
One way to check what's really happening is to use either Fiddler or Firebug. Or both.
Another strategy to use is printing value of request.getRequestURL().toString() before doFilter(), so you can see what requests are being served. It's difficult to pinpoint why are you seeing 2 requests because the cause might be hidden somewhere in your environment or configuration.
Fire up Fiddler and watch the requests being made.
Related
I have a code which does a POST to a URL. The code uses setFixedLengthStreamingMode since it knows the length of POST in advance.
I am having a situation where in some cases the URL could be redirected to something else and since streaming mode is enabled; its not able to follow redirect.
Is there any way to do a check before actually posting the data to see if URL is getting redirected or not? Or am I thinking in wrong direction?
In general, no, there isn't. In a normal web use case though after a POST request done from a submit form you should always get a redirect as per best practices, but this is far from guaranteed. For example, it can do a request if data is similar, and not do it if it is something else. It can always fail with an error.
For some limited use cases there might be some logic that is always followed, but that is case-by-case thing then.
From documentation:
When output streaming is enabled, authentication and redirection
cannot be handled automatically. A HttpRetryException will be thrown
when reading the response if authentication or redirection are
required. This exception can be queried for the details of the error.
So while the redirect will not be handled automatically, and even though you cannot really check for redirect beforehand, what you can do is that you can catch the exception and perform steps yourself based on that.
Okay this is ridiculous: (or probably my design is :)
Here are the URLs that we are using:
/{projectName}/{wallName} - GET only: fetch all win conditions posted to the all
/{projectName}/WinCondition - POST a new Win Condition
/{projectName}/WinCondition/{id} - GET, PUT & DELETE
Now the funny part:
If the code is ordered as above the call POST: /myProject/WinCondition gets routed to the first route with wallName! And thus get a 405.
If I shift the /{projectName}/{wallName} to the bottom then it gets routed correctly!
Now here's what I know:
The default routing mode in Restlet
is MODE_FIRST_MATCH. I set that to
MODE_BEST_MATCH and the order of URLs
still matters! I am unable to access
the 'affinity' score to check what's
the problem/score. Matching mode is Template.MODE_EQUALS.
The question is then this: Do I have to be concerned with how I order the URLs in my java file???? That'll be scary, even from a maintenance point of view.
Any suggestions? Should I redesign my URLs?? But the 'structure' still tends to be the same leading to the same problem
"/{projectName}/{wallName}" and "/{projectName}/WinCondition" will obtain the same score for both FIRST_MATCH and BEST_MATCH so it is still the first in the route list that wins.
But this is really a side effect that you shouldn't get yourself into generally speaking. The problem is that it looks like you propose two routes to two different resource classes for the same URIs (such as "/myProject/WindCondition").
You should really consider redesigning your URIs to prevent such conflict. Here is a suggestion:
/{projectName}/walls/{wallName}
/{projectName}/winCondition
/{projectName}/winCondition/{id]
Otherwise, if relying on routes order scares you, it is possible to customize the default routing logic to take into account the target method for the scoring.
I have a software design question on what's the best way to handle a client javascript program that relies in multiple (but mostly consecutive, not simultaneous), short-lived AJAX calls to the server as a response to user interaction [in my particular case, it will be a facebook-GAE/J app, but I believe the question is relevant to any client(browser)/server design].
First, I asked this question: What is the life span of an ajax call? . Based on BalusC answer (I encourage it to read it there), the short answer is "that's up to the browser". So, right now I do not have really control of what's happening after the server sent the response.
If the main use for an AJAX call is to retrieve data just once from the server, is it possible to manually destroy it? Would xhr1.abort() do that?
Or, the best choice is leave it like that? Would manually closing each connection (if even possible) add too much overhead to each call?
Is it possible to manually set the limit per domain?
And last (but not least!), should I really worry about this? What would be a number of calls large enough to start delaying the browser (specially some IE browsers with the leak bug that BalusC mentioned in the other question? Please, bear in mind that this is my first javascript/java servlets project.
Thank you in advance
The usage paradigm for XHR is that you don't have to worry about what happens to the object -- the browser's engine takes care of that behind the scenes for you. So I don't see any point in attempting to "improve" things manually. Browser developers are certainly aware that 99.9999% of JS programmers do not do that, so they have not only taken it into account but probably optimized for that scenario as well.
You should not worry about it unless and until you have a concrete problem in your hands.
As for limiting the number of AJAX calls per domain (either concurrent outstanding calls, or total calls made, or any other metric you might be interested in), the solution would be the venerable CS classic: add another layer of abstraction.
In this case, the extra layer of abstraction would be a function through which all AJAX calls would be routed through; you can then implement logic that tracks the progress of each call (per domain if you want it to) and rejects or postpones incoming calls based on that state. It won't be easy to get it correctly, but it's certainly doable.
However, I suggest also not worrying about this unless and until you have a concrete problem in your hands. :)
Update:
Browsers do enforce their own limits on concurrent AJAX calls; there's a very good question about that here: How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?
Also, as T. J. Crowder mentions in the comments: make sure you are not keeping references to XHR objects when you are done with them, so that they can be garbage collected -- otherwise, you are creating a resource leak yourself.
Second update:
There is a good blog post about reusing XHR here -- it's actually the start of a chain of relevant posts. On the down side, it's dated and it doesn't come to any practical conclusion. But it covers the mechanics of reusing XHR well.
If the main use for an AJAX call is to retrieve data just once from the server, is it possible to manually destroy it? Would xhr1.abort() do that?
It only aborts the running request. It does not close the connection.
Or, the best choice is leave it like that? Would manually closing each connection (if even possible) add too much overhead to each call?
Not possible. It's the browser's responsibility.
Is it possible to manually set the limit per domain?
Not possible from the server side on. This is a browser specific setting. Best what you could to is to ask in some page dialog the enduser to change the setting if not done yet. But this makes after all no sense, certainly not if the enduser does totally not understand the rationale behind this.
And last (but not least!), should I really worry about this? What would be a number of calls large enough to start delaying the browser (specially some IE browsers with the leak bug that BalusC mentioned in the other question? Please, bear in mind that this is my first javascript/java servlets project.
Yes, you should certainly worry about browser specific bugs. You want your application to work without issues, do you? Why wouldn't you just use an existing ajax library like jQuery? It has already handled all nasty bugs and details under the covers for you (which is many more than only MSIE memory leaking). Just call $.ajax(), $.get(), $.post() or $.getJSON() and that's it. I wouldn't attempt to reinvent the XHR handling wheel when you're fairly new to the materials. You can find some jQuery-Servlet communication examples in this answer.
I have two questions. The first is do Filters add a lot of overhead to request. We have a filter and it is set to run on the URL pattern /*. This means it also runs on all the image request. I think that this is not good for performance, but my co-workers think that it doesn't matter if the filter runs 5 or 6 times per request because the filter only has a couple of if statements.
Is there a way to have the filter run once per request, ignoring the image request.
Thanks Doug
Measuring is knowing. If well-written, I'd say, it's negligible. But if it's for example grabbing the session regardless of it's been created (and thus there's a chance that it will unnecessarily be created), then it may have a noticeable impact on performance and/or memory usage because creation of sessions isn't per-se cheap and sessions are stored in sever's memory for a longer term than the requests.
You may want to replace the url-pattern of /* by *.jsp or to move the restricted pages to a specific folder, e.g. /secured, /private, /pages, etc and alter the url-pattern accordingly to /secured/*, /private/*, /pages/*, etc and put all the static content in a different place, e.g. /static. This way the filter won't be invoked for static content anymore.
First, I agree with the Profile-first approach.
Second, as far as I know it depends, web-server use the same technique to invoke a specific servelt(/JSP) as they use for filters.
In case the filter is filtering a static resource(e.g. jpg file), it's a bit of a waste,
In case the filter is filtering a dynamic resource (e.g. Servlet) it's negligible..
(Most of the Java web frameworks like struts and Jboss-seam are using filters heavily..)
It almost never useful to speculate about the performance implications of code without first profiling it. Unless the code being proposed in the filters is doing some operations you know to be slow then measure first before optimising.
Remember even though when you are writing a servlet it may seem like the only thing that happens is the code in your doGet() or doPost() methods a lot of other things happen before your servlet/filter code gets invoked. The servlet container processes the HTTP request bundles it up in Java objects and does all sorts of other processing before it hands over to your code.
If your servlet filters really are only a couple of if statements operating on data that is cheap to get (such as the request itself), it is unlikely this is going to be an issue for you.
I need to get hold of the request object in Java code. I can't pass this object down to my code for certain reasons. Is there any way I can say something like: getCurrentHTTPServletRequest?
It is safe for me to assume that I am in a Servlet Context.
Well you should pass it down if you need it. Anything else you do is going to be ugly, basically.
You could use a ThreadLocal variable - basically set the context for that particular thread when you get the request, and then fetch it later on. That will work so long as you only need to get at the request within the thread that's processing it - and so long as you don't do any funky asynchronous request handling. It's brittle though, for precisely those reasons.
However, I would strongly advise you to be explicit about your dependencies instead. Either pass the servlet request down, or just the bits that you need.
Assuming you're not able to pass the request object down the call stack, then some kind of sharing mechanism becomes necessary, which is not ideal, but sometimes necessary.
Spring provides the RequestContextFilter for just this purpose. It uses ThreadLocal, and allows the code to fetch the current request via RequestContextHolder. Note that this filter does not require you to use any other part of Spring:
Servlet 2.3 Filter that exposes the
request to the current thread, through
both LocaleContextHolder and
RequestContextHolder. To be registered
as filter in web.xml.
This filter is mainly for use with
third-party servlets, e.g. the JSF
FacesServlet. Within Spring's own web
support, DispatcherServlet's
processing is perfectly sufficient.
If you're going to use ThreadLocal, then better to use an existing, working solution, rather than risk bugs creeping in, which ThreadLocal code is prone to.
Jon Skeet said practically everything, but one clarification to his advice "just the bits that you need" - if you need your request parameters passed down, but you don't need a dependency on HttpServletRequest, pass request.getParameterMap().
And extending a bit on the ThreadLocal option - you can have a Filter which handles all incoming requests, and sets the request in a
public final static ThreadLocal<HttpServletRequest> httpServletRequestTL =
new ThreadLocal<HttpServletRequest>();
Because you are setting it on each request (careful with the filter mapping), you won't have to worry about the servlet-container thread pool - you will always have the current request.
P.S. this is the logic behind the spring utility proposed by skaffman - I join him recommending the stable component, rather than making your own.
There is no servlet API to do this. However, Tomcat does provide an API call to do this,
HttpServletRequest request = (HttpServletRequest)org.apache.catalina.core.ApplicationFilterChain.getLastServicedRequest();
This will get the last request passed to a servlet for servicing from the current thread.
For this to work, the Tomcat must be in "Strict Servlet Compliance" mode. If not, you need to enable it by adding this JVM parameter:
org.apache.catalina.STRICT_SERVLET_COMPLIANCE=true
Assuming the top-level servlet really is taboo for some crazy business-related reason, there is still the option of defining a ServletFilter to pre-view the request and stuff it into a ThreadLocal. Assuming that the web.xml is not also sacrosanct.
But I agree with Jon Skeet in that this would be very ugly. I'd code this up and then try to find a different job. :)
Actually, given the fact that a filter can totally wrest away control from the receiving servlet, you could use this technique to divert the code to a servlet of your own, do whatever you want, and THEN run the other, "official" servlet... or anything else along those lines. Some of those solutions would even allow you to deal correctly and robustly with your request data.