I am implementing a Java enterprise application and declared a Filter for every request, so how does the server tracks this request, do it create a new filter object for every request, or their is only one filter handling all request, in other words are java web filter singletone?
-
I am not sure, but init() and destroy() are called only once, but for every request it has to go through doFilter.... this behaviour is same as servlet init, destroy or service methods. – AurA Feb 12 '14 at 06:56
-
Related: http://stackoverflow.com/q/3106452 – BalusC Oct 09 '15 at 19:07
2 Answers
First, let's review the definition of Singleton Pattern (emphasis mine):
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
When you declare a class that implements the Filter
interface, it needs a public
constructor (usually the default constructor) so the application server could instantiate it. Thus, by doing this, the Filter
is not a singleton.
Note that the application server will maintain a single instance per application context e.g. per a deployed web application, but this is not the same as having a singleton. Why? Because you or another programmer can carelessly create an instance of this class (even if it doesn't make use of the instance).

- 85,076
- 16
- 154
- 332
-
5Not a singleton, but equivalent to "@ApplicationScoped" in CDI essentially. – Jonathan S. Fisher Jun 04 '14 at 18:13
The answer is depended on how you define it in web.xml.
For example, this fragment of web.xml, create one object of Filter1
<filter>
<filter-name>Filter1</filter-name>
<filter-class>com.surasin.test.Filter1</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
But this framgemet of web.xml, create two objects of Filter1
<filter>
<filter-name>Filter1</filter-name>
<filter-class>com.surasin.test.Filter1</filter-class>
<init-param>
<param-name>my-param</param-name>
<param-value>my-param-value</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>Filter1</filter-name>
<filter-class>com.surasin.test.Filter1</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

- 5,520
- 4
- 32
- 40