Are Java Singleton Filters

I am implementing an enterprise Java application and declaring a filter for each request, since the server is monitoring this request, does it create a new filter object for each request, or is there only one filter that processes the entire request, in other words java web filter singleletone?

+6
source share
2 answers

First, consider the definition of a Singleton Pattern (highlighted by me):

In software development, a singleton pattern is a design pattern that restricts the instantiation of a class to a single object .

When you declare a class that implements the Filter interface, it needs a public constructor (usually this is the default constructor), so the application server can create one. Thus, while Filter not single.

Note that the application server will support one instance for each application context, for example. for a deployed web application, but this is not the same as having a singlet. What for? Since you or another programmer can carelessly create an instance of this class (even if it does not use an instance).

+13
source

The answer depends on how you define it in web.xml.

For example, this snippet of web.xml, create one Filter1 object

  <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 frame is from web.xml, create two Filter1 objects

  <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> 
0
source

All Articles