Java EE Listener and filter Basics

Source: Internet
Author: User

The servlet program consists of Servlet,filter and listener, where the listener is used to listen to the servlet container context.

Listeners are typically divided into three categories: the Servletcontex listener based on the servlet context, the session-based HttpSession listener, and the request-based ServletRequest listener.

    • Servletcontex Listener
Servletcontex, also known as application, is the entire servlet container life cycle, which is created when the system is started and destroyed when the system shuts down, which usually holds some very common data, but it is not recommended to store too much Otherwise, the long-term occupy memory space can affect server performance. The Servletcontex-based listener can inherit two interfaces and implement the corresponding methods in the interface: The Servletcontextlistener interface defines two methods contextinitialized and contextdestroyed, Triggered when Servletcontex is created and destroyed, respectively, and the Servletcontextattributelistener interface defines three methods attributeadded, Attributeremoved and attributereplaced, respectively, are triggered when you add attribute values to Servletcontex, delete attribute values, and replace property values. The following creates a application-based listener:
/*** Application Listener, application in servlet is ServletContext *@authorAdministrator*/   Public classApplicationlistenerImplementsServletcontextlistener, Servletcontextattributelistener {/*** Event triggered when application is destroyed*/@Override Public voidcontextdestroyed (servletcontextevent arg0) {System.out.println ("Application Destruction:" +Arg0.getservletcontext ()); }            /*** method that is triggered when application is initialized*/@Override Public voidcontextinitialized (servletcontextevent arg0) {System.out.println ("Application created:" +Arg0.getservletcontext ()); }            /*** method to trigger when adding attribute values in application*/@Override Public voidattributeadded (servletcontextattributeevent arg0) {System.out.println ("Application Add new attribute: key=" +arg0.getname () + "value=" +Arg0.getvalue ()); }            /*** Method triggered when attribute values are deleted in application*/@Override Public voidattributeremoved (servletcontextattributeevent arg0) {System.out.println ("Application Remove attribute: key=" +arg0.getname () + "value=" +Arg0.getvalue ()); }            /*** method triggered when replacing attribute values in application*/@Override Public voidattributereplaced (servletcontextattributeevent arg0) {System.out.println ("Application Replace attribute: key=" +arg0.getname () + "value=" +Arg0.getvalue ()); }    }  

Finally, you need to register the listener in Web. XML, the registration method is very simple, note that tags <description> and <display-name> are not required:

<listener>      <description>application listener</description>      <display-name> Application_listener</display-name>      <listener-class> com.bless.listener.application.applicationlistener</listener-class>  </listener>  

The Java Web project is then started and the listener runs.

    • Session Listener
Session for the people who do Web projects should be very familiar with, the session life cycle is a user's session, simply say when a user enters a site, the site server has created a Session object for the user, Any user action within the site is within the session cycle. Myth: Some people think I go to a website, then close the browser, my session has been destroyed. In fact, because the session is stored on the server side, the server can not actively capture the browser shutdown events, even if the browser is closed, the session object still exists in the server. So if you are writing a Web application, be sure to consider when the session is destroyed, there are two ways to destroy the Session object: one is to call the session invalidate method, The other is to define the session expiration time Session-timeout in Web. Xml. The session listener also has two interfaces, which are similar in function to the Servletcontex described earlier: Httpsessionlistener is used to listen for events created and destroyed by the session, Httpsessionattributelistener is used to listen for events that the session property assigns, deletes, and replaces:
/*** Session Listener *@authorAdministrator*/   Public classSessionlistenerImplementsHttpsessionlistener, Httpsessionattributelistener {Vector<HttpSession> listsession =NULL; /*** Create Session Call Method * Place Session object into Listsession collection*/       Public voidsessioncreated (httpsessionevent arg0) {synchronized( This) {              if(Listsession = =NULL) {listsession=NewVector();          }} listsession.add (Arg0.getsession ()); System.out.println ("\ n \ nyou Create a session:" +arg0.getsession ()); System.out.println ("[Session currently in existence:]");  for(HttpSession session:listsession) {System.out.println ("--->" +session); }      }            /*** Method of destroying session call * Remove Listsession set corresponding session value*/       Public voidsessiondestroyed (httpsessionevent arg0) {listsession.remove (arg0.getsession ()); System.out.println ("\ Nyou destroy a session:" +arg0.getsession ()); System.out.println ("[Session currently in existence:]");  for(HttpSession session:listsession) {System.out.println ("--->" +session); }      }            /*** Method Called when the session property is added*/       Public voidattributeadded (httpsessionbindingevent arg0) {System.out.println ("\ n \ nyou Add a session-->key:" +arg0.getname () + "property value:" +Arg0.getvalue ()); }      /*** Method Called when session property overrides*/        Public voidattributereplaced (httpsessionbindingevent arg0) {System.out.println ("\ n \ nyou Overwrite a session-->key:" +arg0.getname () + "property value:" +Arg0.getvalue ()); }            /*** Method Called when session properties are removed*/       Public voidattributeremoved (httpsessionbindingevent arg0) {System.out.println (\ n \ nyou Delete a session-->key: "+arg0.getname () +" property value: "+Arg0.getvalue ()); }  }  

Define the appropriate listener configuration in Web. xml:

<listener>      <listener-class>com.bless.listener.session.sessionlistener</listener- class>    </listener>  <!--session Timeout configuration-    <session-config>      < Session-timeout>1</session-timeout>    </session-config>  
    • Request Listener
The request listener is used in much the same way as before, and a request life cycle is the entire process of sending requests to the server to respond to the final response to the page. The request listener corresponds to the Servletrequestlistener,servletrequestattributelistener interface, and the corresponding interface is implemented according to different requirements.
/*** Request Event Listener *@authorAdministrator*/   Public classRequestlistenerImplementsServletrequestlistener, Servletrequestattributelistener {@Override Public voidrequestdestroyed (servletrequestevent arg0) {System.out.println ("Request Destroy:" +arg0.getservletrequest ()); } @Override Public voidrequestinitialized (servletrequestevent arg0) {System.out.println ("Request creation:" +arg0.getservletrequest ()); } @Override Public voidattributeadded (servletrequestattributeevent arg0) {System.out.println ("Request attribute added key=" +arg0.getname () + "value=" +Arg0.getvalue ()); } @Override Public voidattributeremoved (servletrequestattributeevent arg0) {System.out.println ("Request Property Delete key=" +arg0.getname () + "value=" +Arg0.getvalue ()); } @Override Public voidattributereplaced (servletrequestattributeevent arg0) {System.out.println ("Request attribute replace key=" +arg0.getname () + "value=" +Arg0.getvalue ()); }    }  

Web. XML configuration:

<listener>      <listener-class>com.bless.listener.request.requestlistener</listener- class>  </listener>  
    • Filter filters
When a page sends a request, a request that conforms to the filter range first enters the filter, and the filter can perform some filtering operations: such as encoding format, session validation, logging, and so on. And these functions are written by their own filter implementation. To implement a filter, you need to inherit the filter interface to implement the Init, Dofilter, and destroy methods, which are three methods that are executed when the filter is initialized, the filter is running, and the filter is destroyed. The following code, is a character set filter, each request will set the character set encoding format, note that each request will run the Dofilter method, after filtering you need to call Filterchain.dofilter within the method so that the request to access the specified servlet. Assuming you do not want to request access to the next servlet, you can choose to redirect to the specified page.
/**  *   * @author: Bless<[email protected]> * Create time:2011-5-10 PM 10:38:19 * Description: Character Set format filter **/   Public classEncodingfilterImplementsFilter {//default encoding format UTF-8    Private Static FinalString Default_encode = "UTF-8"; PrivateString EncodeName;//encoding Format       Public voiddestroy () {}/**      * @seeFilter#dofilter (ServletRequest, Servletresponse, Filterchain)*/       Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {Try {              if(EncodeName = =NULL|| "". Equals (Encodename.trim ()))                  {request.setcharacterencoding (Default_encode);              Response.setcharacterencoding (Default_encode); } Else{request.setcharacterencoding (encodename); }          } Catch(unsupportedencodingexception e) {Throw NewUnsupportedencodingexception ("Encoding format filter error, please verify that Web. XML is filled in with the correct encoding format");      } chain.dofilter (request, response); }        /**      * @seefilter#init (filterconfig)*/       Public voidInit (Filterconfig fconfig)throwsservletexception {//get the <param-name>encodeName</param-name> value of the Web. XML Configuration         This. Setencodename (Fconfig.getinitparameter ("EncodeName")); }         PublicString Getencodename () {returnEncodeName; }         Public voidsetencodename (String encodename) { This. EncodeName =EncodeName; }    }  

The filter is then defined in Web. XML, and the label Init-param can be configured with a parameter, which is obtained by using the Init method parameter Filterconfig.getinitparameter in the filter:

<filter>      <filter-name>encoding</filter-name>      <filter-class> com.mt.filter.encodingfilter</filter-class>      <init-param>          <param-name> encodename</param-name>          <param-value>GBK</param-value>      </init-param>    </ filter>    <filter-mapping>      <filter-name>encoding</filter-name>      < url-pattern>/*</url-pattern>    </filter-mapping>  

Transferred from: http://blessht.iteye.com/blog/1164492

http://www.iteye.com/topic/483158

http://chinaxxren.iteye.com/blog/811604

http://blog.csdn.net/fyxxq/article/details/9731747

http://ooft.iteye.com/blog/551498

http://www.iteye.com/topic/82565

Java EE Listener and filter Basics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.