Software Development Engineer (JAVA) Intermediate exam syllabus----Five Java EE Web Advanced Component Development (ii) Web Filter component technology, Web listener component technology;

Source: Internet
Author: User
Tags set set

first, what is a servlet filter?

Servlet filters are small WEB components that intercept requests and responses to view, extract, or somehow manipulate data that is being exchanged between the client and server. Filters are WEB components that typically encapsulate some functionality, though important, but are not conclusive for processing client requests or sending responses. Typical examples include recording data about requests and responses, handling security protocols, managing session properties, and so on. Filters provide an object-oriented, modular mechanism for encapsulating common tasks into pluggable components that are declared by a configuration file and processed dynamically.

The servlet filters combine a number of elements, making the filter a unique, powerful, and modular Web component. The servlet filter has the following characteristics:
1. Declarative : The filter is declared by the XML tag in the WEB Deployment Descriptor (XML). This allows you to add and remove filters without having to change any application code or JSP pages.
2. Dynamic : The filter is called by the Servlet container at runtime to intercept and process requests and responses.
3. Flexible : Filters are widely used in Web processing environments, covering many of the most common auxiliary tasks, such as logging and security. Filters are also flexible because they can be used to perform preprocessing and post-processing on direct calls from clients, and to handle requests that are dispatched between WEB components behind a firewall. Finally, you can link the filters to provide the necessary functionality.
4. Modular: by encapsulating application processing logic into a single class file, the filter defines a modular unit that can be easily added to or removed from the request/response chain.

5. Portable: Like many other aspects of the Java platform, servlet filters are portable across platforms and containers, further supporting the modular and reusable nature of the Servler filter.
6. Reusable: thanks to the modular design of the filter implementation class and the declarative filter configuration, filters can be easily used across different projects and applications.
7. Transparent: include filters in the request/response chain, which is designed to complement (rather than in any way replace) the core processing provided by a servlet or JSP page. As a result, filters can be added or removed as needed without breaking the servlet or JSP pages.

So a servlet filter is a modular reusable component that is flexibly declared through a configuration file. Filters dynamically process incoming requests and outgoing responses, and can add or remove them transparently without modifying the application code. Finally, filters are independent of any platform or Servlet container, allowing them to be easily deployed to any compatible Java EE environment.

Two Servlet filter Architecture
As its name implies, the servlet filter is used to intercept incoming requests and/or outgoing responses and to monitor, modify, or somehow process the traffic being passed. Filters are self-contained, modular components that can be added to the request/response chain or deleted without affecting other WEB components in the application. Filters are only run-time processing of changes to requests and responses, so they should not be embedded directly into the Web application framework, unless they are implemented through a well-defined standard interface in the Servlet API.

A WEB resource can be configured without a filter associated with it (which is the default), associated with a single filter (which is typical), or even associated with a filter chain. So what exactly does the filter do? Like a servlet, it accepts requests and responds to objects. The filter then examines the request object and decides to forward the request to the next component in the chain, or aborts the request and sends a response back directly to the client. If the request is forwarded, it is passed to the next resource in the chain (another filter, servlet, or JSP page). After the request has managed to pass through the filter chain and is processed by the server, a response is sent back in reverse order through the chain. This gives each filter an opportunity to process the response object as needed.


When filters are first introduced in the Servlet 2.3 specification, they can only filter the content between the Web client and the specified Web resource accessed by the client. If the resource then dispatches the request to another Web resource, the filter cannot be applied to any requests that are being delegated behind the scenes. The 2.4 specification eliminates this limitation. The servlet filter can now be applied anywhere in the Java EE WEB environment where the request and response objects exist. Therefore, a servlet filter can be applied between a client and a servlet, between a servlet and a servlet or a JSP page, and between each JSP page that is included.

Third, step

Go through three steps:
1, write the Filter implementation class program
2. Add the filter to the Web application (by declaring it in the Web Deployment descriptor/web.xml)
3. Package and deploy the filter with the application

3 interfaces:Filter ,filterchain , and filterconfig.
From a programmatic point of view, the filter class implements the filter interface and then uses the Filterchain and Filterconfig interfaces. A reference to the filter class is passed to the Filterchain object to allow the filter to pass control to the next resource in the chain. The Filterconfig object is provided by the container to the filter to allow access to the initialization data of the filter.

Four, filter life cycle method
1. Init (): This method is called when the container instantiates a filter, and it is primarily designed to make the filter ready for processing. This method takes an object of type Filterconfig as input.

2, DoFilter (): As with the servlet having a service () method (which calls Dopost () or doget ()) to process the request, the filter has a single method for handling requests and responses---doFilter (). This method accepts three input parameters: a servletrequest, a servletresponse, and a Filterchain object.

3, Destroy (): As you can imagine, this method performs any cleanup operations that may need to occur before automatic garbage collection.

The following is a filter instance that completes the character set conversion. First, complete the filter code, read the configuration parameters in the Init method, and complete the conversion of the character set in Dofilter.

   Package myproj.filter;   Import java.io.IOException;   Import Javax.servlet.Filter;   Import Javax.servlet.FilterChain;   Import Javax.servlet.FilterConfig;   Import javax.servlet.ServletException;   Import Javax.servlet.ServletRequest;   Import Javax.servlet.ServletResponse;     public class Setcharacterencodingfilter implements filter{//defines the substituted character set and reads String Newcharset from the configuration parameters of the filter; public void Destroy () {} public void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) thro WS IOException, servletexception  {  //Processing request Character Set    request.setcharacterencoding (new      CharSet);  //Processing response character Set    Response.setcontenttype ("text/html;charset=" +newcharset); Pass to the next filter, if there is no filter that is the requested resource Chain.dofilter (Request,response);   public void init (Filterconfig filterconfig) throws servletexception {  //derive initialization parameters from the configuration of the filter If not, use the default value     if (Filterconfig.getiniTparamter ("Newcharset")!=null) {    Newcharset = Filterconfig.getinitparamter ("Newcharset");       }else{    Newcharset = "GB2312"; } }}
Initialize:The init () method is called when the container loads the filter for the first time. The class contains a reference to the Filterconfig object in this method. The character set set in the configuration file is obtained through the Filterconfig object.
Filter:Most of the time the filter is consumed here. The DoFilter () method is called by the container while passing in a reference to the ServletRequest, Servletresponse, and Filterchain objects in the request/response chain respectively. This completes the setting of the response page character set.
Destruction:The container immediately calls the Destroy () method before garbage collection, so that any necessary cleanup code can be executed.

Deploy a servlet filter to configure filters in the Web. xml file

  <!--filter configuration-   <filter>     <filter-name>Encoder</filter-name>     <filter-class >myproj.filter.SetCharacterEncodingFilter</filter-class>     <!--initialization Parameters--     <init-param  >       <param-name>newcharset</param-name>       <param-value>gb2312</param-value>  </init-param>   </filter>   <!--filters associated with URLs--   <filter-mapping>      < filter-name>encoder</filter-name>      <url-pattern>/*</url-pattern>   </ Filter-mapping>
Compile the Setcharacterencodingfilter class, compile, you need to put the Java Servlet API package Servlet-api.jar into the Classpath, the compiled class is placed in the Web-inf\classes directory of the Web application, And the directory structure should be consistent with the structure of the package.

Five, the application of the filter

1. Set the character encoding filter: Specify what character encoding to use to handle the Chinese issue of the page by configuring the parameter encoding.
2, using the filter to achieve URL-level permission authentication: in the actual development we often map some of the sensitive operation of the servlet to some special directories, and filter to protect these special directories, Restricting access to resources in these directories is restricted to users who can only have the appropriate access root.
3, realize the user automatic Landing filter: After the user login successful, send a cookie named user to the client, the value of the cookie is the user name and password after encryption. A filter can be used to check whether a request has a cookie named user. If so, verify it.
4. Implement log of application access: for all requests that arrive at the system, the filter collects information such as browser type, time of day, forwarding URL, and logs records.
5. XSLT Transformations: Whether you use a mobile client or an XML-based Web service, the ability to perform conversions between XML grammars without having to embed logic in your application is absolutely priceless.

six , the servlet listener is used to monitor the occurrence of some important events, listener objects can be done before, after the occurrence of some necessary processing.

Interface: currently Servlet2.4 and JSP2.0 have a total of 8 listener interfaces and 6 event classes ,

The listener and corresponding event are as follows:

1, Servletcontextlistener---servletcontextevent

2, Servletcontextattributelistener---servletcontextattributeevent

3, Httpsessionlistener---httpsessionevent

4, Httpsessionactivationlistener---httpsessionevent

5, Httpsessionattributelistener---httpsessionbindingevent

6, Httpsessionbindinglistener---httpsessionbindingevent

7, Servletrequestlistener---servletrequestevent

8, Servletrequestattributelistener---servletrequestattributeevent

(i) ServletContext related monitoring interface   

An instance of ServletContext can access the application's global objects and the variables in the initialization phase. In the JSP file,application is an instance of ServletContext , created by default by the JSP container. The Getservletcontext () method is called in the Servlet to get an instance of ServletContext. Note: The global object is the application scope object, and the variables in the initialization phase refer to the variables set by the <context-param> element in Web. XML, and its scope is also application range, for example:

<context-param>

<param-name>Name</param-name>

<param-value>browser</param-value>

</context-param>

When the container starts, a application-scoped object is created to get this variable in the JSP Web page: String name = (string) application.getinitparameter ("name");

Or when using el: ${initpara.name} If in the servlet, get the value method of name: String name = (string) servletcontext.getinitparameter ("name");

1, Servletcontextlistener: for monitoring the launch and destruction of the Web application events, listener classes need to implement Javax.servlet.ServletContext
2, Listener interface. Servletcontextlistener is a listener for ServletContext, if ServletContext changes, such as when the server is started ServletContext is created, the server shuts down ServletContext will be destroyed.

Servletcontextlistener interface Method:
void contextinitialized (Servletcontextevent SCE) notifies the object being accepted that the application has been loaded and initialized.
void contextdestroyed (Servletcontextevent SCE) notifies the object being accepted that the application has been loaded.

Methods in Servletcontextevent:
ServletContext Getservletcontext () obtains ServletContext object


Servletcontextattributelistener: An event used to listen to changes in the properties of a web app, including: Adding Properties, deleting properties, modifying properties, The listener class needs to implement the Javax.servlet.ServletContextAttributeListener interface.

Servletcontextattributelistener interface Method:
void attributeadded (Servletcontextattributeevent scab) notifies an object that is listening if an object is joined to a range of application
void attributeremoved (Servletcontextattributeevent scab) notifies an object that is listening if an object is removed from the range of application
void attributereplaced (Servletcontextattributeevent scab)

Methods in Servletcontextattributeevent:
Java.lang.String GetName () The name of the callback property
Java.lang.Object the value of the GetValue () callback Property


Second, httpsession related monitoring interface
Through the HttpSession instance, we can realize the session tracking, and the HttpSession related listener interface defines the processing related to the conversation.

1. Httpsessionbindinglistener interface

Note: The Httpsessionbindinglistener interface is the only listener that does not need to be set in Web. XML when our class implements the Httpsessionbindinglistener interface, Whenever the object is added to the session range (that is, when the setattribute method of the HttpSession object is called) or removed from the session range (that is, when the RemoveAttribute method of the HttpSession object is called or the session When time is out), the container automatically calls the following two methods, respectively:

void Valuebound (Httpsessionbindingevent event)

void Valueunbound (Httpsessionbindingevent event)

2. Httpsessionattributelistener interface

Httpsessionattributelistener listens for properties in the httpsession operation. When an attribute is added to the session, the attributeadded (httpsessionbindingevent se) method is fired; When a property is deleted at the session, the attributeremoved is fired ( Httpsessionbindingevent se) method, which fires the attributereplaced (httpsessionbindingevent se) method when the session property is reset. This is more like Servletcontextattributelistener.
3. Httpsessionlistener interface

Httpsessionlistener Monitor the operation of the HttpSession. The session Created (Httpsessionevent se) method is fired when a session is created, and the sessiondestroyed (httpsessionevent se) method is fired when a session is destroyed. The 4.HttpSessionActivationListener interface is primarily used when the same session is transferred to a different JVM.
third, ServletRequest monitoring interface

1. The Servletrequestlistener interface is similar to the Servletcontextlistener interface, which defines operations related to ServletRequest objects.

2, Servletrequestattributelistener interface and Servletcontextattributelistener interface is similar, but the interface is listening to servletrequest property changes.
The following instance Mysessionlistener is used to monitor changes in the session.

Package Sample;import Javax.servlet.servletcontext;import Javax.servlet.servletcontextevent;import Javax.servlet.servletcontextlistener;import Javax.servlet.http.httpsessionattributelistener;import Javax.servlet.http.httpsessionbindingevent;import Javax.servlet.http.httpsessionevent;import Javax.servlet.http.httpsessionlistener;import Javax.servlet.http.httpsessionactivationlistener;import Javax.servlet.http.httpsessionbindinglistener;import Java.io.printwriter;import Java.io.FileOutputStream;public Final class Mysessionlistener implements Httpsessionactivationlistener, Httpsessionbindinglistener, Http   Sessionattributelistener, Httpsessionlistener,servletcontextlistener {ServletContext context;   int users=0; Httpsessionactivationlistener public void sessiondidactivate (httpsessionevent se) {logout ("Sessiondidactivat   E ("+se.getsession (). GetId () +") "); }  public void sessionwillpassivate (httpsessionevent se)    {        Logout ("Sessionwillpassivate (" +se.getsession (). GetId () + ")");  }// httpsessionactivationlistener  //httpsessionbindinglistener   public void ValueBound ( Httpsessionbindingevent event)    {                Logout ("Valuebound (" +event.getsession () getId () +event.getvalue () + ")");  }    public void Valueunbound (Httpsessionbindingevent event)    {                    Logout ("Valueunbound (" + Event.getsession (). GetId () +event.getvalue () + ")";  }  //httpsessionattributelistener     public void attributeadded (Httpsessionbindingevent event) {        Logout ("attributeadded" + event.getsession (). GetId () + "', '" +             Event.getname () + "', '" + event.getvalue () + "')");   }  public void attributeremoved (Httpsessionbindingevent eve NT) {  Logout ("attributeremoved ('" + event.getsession (). GetId () + "', '" +event.getname () + "', '" + event.getval  UE () + "')"); }  public void attributereplaced (httpsessionbindingevent se) {             Logout ("attributereplaced ('" +se.getsession (). GetId () + ", '" +se.getname () + "', '" +se.getvalue () + "  ')"); }//httpsessionattributelistener //httpsessionlistener  public void sessioncreated (HttpSessionEvent event ) {  users++;  Logout ("sessioncreated ('" + event.getsession (). GetId () + "'), currently has" +users+ "users");  con  Text.setattribute ("Users", new Integer (users)); } public void Sessiondestroyed (Httpsessionevent event) {        users--;         Logout ("sessiondestroyed" + event.getsession (). GetId () + "'), currently has" +users+ "user");        context.setattribute ("Users", new Integer (users); }/ /httpsessionlistener   //servletcontextlistener  public void contextdestroyed ( Servletcontextevent SCE) {        logout ("contextdestroyed ()-- ServletContext is destroyed ");        This.context = null;   }  public void contextinitialized (Servletcontextevent sce) {        This.context = Sce.getservletcontext ();        Logout ("contextinitialized () and ServletContext initialized "); }//servletcontextlistener  private void Logout (String message) {    PrintWriter out=null;    try{       out=new PrintWriter (new        FileOutputStream ("D:\\temp\\session.txt", true));        OUT.PRINTLN (New JAVA.util.date (). toLocaleString () + ":: Form Mysessionlistener:" + message);       Out.close ();    } catch (Exception e) {       out.close ();        e.printstacktrace ();    }}}
















Software Development Engineer (JAVA) Intermediate exam syllabus----Five Java EE Web Advanced Component Development (ii) Web Filter component technology, Web listener component technology;

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.