Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Filters Performance Question

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

like image 741
Doug Avatar asked Jul 22 '10 18:07

Doug


People also ask

What is doFilter () method in Java?

The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

What is filter in Java with example?

A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the web.

How filters are called in Java?

The Java Servlet specification version 2.3 introduces a new component type, called a filter. A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.


2 Answers

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.

like image 127
BalusC Avatar answered Sep 21 '22 21:09

BalusC


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

like image 20
DuduAlul Avatar answered Sep 23 '22 21:09

DuduAlul