Pregunta

Hay filtros y oyentes de funcionalidad en el servlet. Quiero saber diferencia exacta entre el filtro y el oyente.

¿Fue útil?

Solución

Servlet filtro se utiliza para el control de petición y respuesta del cliente para el servlet, o para modificar la petición y la respuesta, o para auditoría y registro.

Servlet Listener se utiliza para escuchar a los acontecimientos en los contenedores una web, como cuando se crea una sesión, o realiza un atributo en una sesión o si pasivar y activar en otro recipiente, para suscribirse a estos eventos se pueden configurar oyente en web.xml, por ejemplo HttpSessionListener.

Otros consejos

Los filtros se utilizan para procesar las solicitudes de pre y post. Mira el javax.servlet.Filter en su tomcat / jboss / otro javadoc recipiente.

Donde como los oyentes son como factores desencadenantes que se pueden unir a los eventos en el servidor de aplicación (Usemos el término contenedor aquí). Con los oyentes puede realizar un seguimiento a nivel de aplicación, a nivel de sesión, los cambios del ciclo de vida, cambios en los atributos etc. Las interfaces implementadas son interfaz javax.servlet.Listener.

En base a las respuestas de los @fnt s adelante, voy a tratar de aclarar un poco más. Los oyentes son objeto de cambios de ciclo de vida, sin necesidad de tener una solicitud de cliente que entra. Así que para una petición de cliente, podría haber muchos más eventos del ciclo de vida pueden suceder antes de que la solicitud se desecha. Ejemplo: Desea registrar todas las sesiones que el tiempo de espera. Tenga en cuenta que SesionTimeout es un evento de ciclo de vida, lo que puede suceder sin que el usuario tenga que hacer nada. Para un escenario de este tipo, un oyente será apropiado.

A la pregunta de registro, cuando llega una petición. No existe una asignación directa de una nueva solicitud a un detector de eventos equivalentes (evento del ciclo de vida de lectura). Y por lo tanto para cada petición entrante si desea registrar algo, filtro en mi opinión es lo que hay que usar.

Este material de Oracle debe ser capaz de aclarar un poco más y oyentes

HTH

Filtro es igual que un filtro de agua, en la que se filtran los valores entrantes (petición) y salientes (respuesta).

Listener es como escuchar (disparador) -. Siempre que sea necesario, que se llevará a cabo

One important difference is often overlooked: while listeners get triggered for an actual physical request, filters work with servlet container dispatches. For one listener invocation there may be multiple filters/servlet invocations.

Listeners vs Filters

Mapping filters dispatcher types. The link is a bit dated - it doesn't include the Servlet 3.0 Async dispatcher type. One can also specify dispatcher types with the @WebFilter annotation:

import javax.servlet.DispatcherType;
import javax.servlet.annotation.WebFilter;

@WebFilter(servletNames = { "My Servlet" },
    dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD })

Text from Java EE 6

Filter

Filter is an object which transform the request and response (header as well as content).

Listeners

You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when life cycle events occur.

After reading all the answers and blogs this is what I got

Filter

A filter is an object that dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.

Filters typically do not themselves create responses but instead provide universal functions that can be "attached" to any type of servlet or JSP page.

The filter is run before rendering view but after controller rendered response.

A Filter is used in the web layer only as it is defined in web.xml.

Filters are more suitable when treating your request/response as a black box system. They'll work regardless of how the servlet is implemented.

Filters are used to perform filtering tasks such as login authentication ,auditing of incoming requests from web pages, conversion, logging, compression, encryption and decryption, input validation etc.

A Servlet Filter is used in the web layer only, you can't use it outside of a web context.

For more detail on filter http://array151.com/blog/servlet-filter/

Listener

Servlet Listener is used for listening to events in a web container, such as when you create a session or place an attribute in a session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example, HttpSessionListener.

Listeners get triggered for an actual physical request that can be attached to events in your app server .With listeners, you can track application-level, session-level, life-cycle changes, attribute changes etc.

You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when lifecycle events occur.

For more detail : http://array151.com/blog/servlet-listener/

and here is the difference http://array151.com/blog/difference-between-servlet-filter-and-servlet-listener/

While you can modify the current event object within a listener, you cannot halt the execution of the current event handler in a listener. You also cannot clear the event queue from within a listener. Besides the imposed differences in capabilities, they are also intended for different purposes. Listeners tend to focus on interacton between the event handler and the model, while filters tend to focus on interaction between the event handler and the controller.

Source : web

You can easily have a rough idea with the English meaning of those two. Filter is there to filter the content/resource which coming to/going out from a Servlet. In the other hand, Listener is there, to do some related things when something happen to the web application(listening).

Filter:Filter is simply Filtering the Response and request coming from the clients to the servlet.

Listener:is like a trigger when any trigger is occur it take the action.

In short,

Filter is for the Servlet, intercepting the requests and responses.

Listener is for the Web Application, doing important tasks on events in context-level, session-level etc.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top