The difference and use of Java Web Filter and Interceptor

Source: Internet
Author: User
Tags aop generator log log java web

First, filter
1. What is a filter?

A filter is a program that runs on the server prior to the servlet or JSP page associated with it. Filters can be attached to one or more servlet or JSP pages, and can be checked for request information that enters these resources. After this, the filter can be selected as follows:
① calls the resource (that is, the servlet or JSP page) in a regular manner.
② invokes the resource with the modified request information.
③ invokes the resource, but modifies it before sending the response to the client.
④ blocks the resource call and instead goes to another resource, returns a specific status code, or generates a replacement output.

Basic principle of 2.Servlet filter:

When the servlet is used as a filter, it can process the client's request. When processing is complete, it is handed over to the next filter, so that the customer's request is processed one by one in the filter chain until the request is sent to the target. For example, a Web site that has submitted a "Modified registration information" page, when the user completed the modification information and submitted, the server in the process of doing two things: to determine whether the client's session is valid, and the data submitted uniformly encoded. These two tasks can be processed in a filter chain consisting of two filters. When the filter is processed successfully, the submitted data is sent to the final target, and if the filter processing is unsuccessful, the view is distributed to the specified error page.

3. Filter: Just want to choose a B in a bunch of things:

4. Sample Code

在web.xml里面配置自定义的过滤器<filter>   <filter-name>Redirect Filter</filter-name>   <filter-class>com.xx.filter.RedirectFilter</filter-class></filter><filter-mapping> <filter-name>Redirect Filter</filter-name> <url-pattern>/xx/xx/*</url-pattern></filter-mapping>

How to write a custom filterPublicClassRedirectfilterImplementsFilter {PublicvoidDoFilter (ServletRequest request, servletresponse response, Filterchain Filterchain)Throws IOException, Servletexception {Get URL Long startTime =Nullif (log.isdebugenabled ()) {startTime = System.currenttimemillis ();} HttpServletRequest HttpRequest = (httpservletrequest) request; String URL = Httprequest.getrequesturl (). toString ();if (url = =null | | Url.trim (). Length () = =0) {Return }if (Url.indexof (lucenecreatemapping)! =-1 | | url.indexof (lucenesearchmapping)! =-1) {dofilterforxxx ( Request, response, URL); } else {doxxxx (request, response, URL);} if (log.isdebugenabled ()) { Long endTime = System.currenttimemillis (); Thread CurrentThread = Thread.CurrentThread (); String threadname = Currentthread.getname (); Log.debug ("[" + ThreadName + "]" + "<" + This.getclass (). GetName () + " " + URL + "" + (Endt Ime-starttime) + "MS"); }//Activates the next filter filterchain.dofilter (request, Response);}}          
Example2//fill 100 balls with random letter tags list< string> array = new arraylist<> (); Random r = new random (); String[] balls = new string[]{ "A",  " B ", " C "}; for (int i = 0; i < 100; i++) array.add (Balls[r.nextint (3)]);  Just take out the B. Do not understand the self-learning Java 8array = array.stream (). Filter (Ball Ball.equals ( "B"). Collect (Collectors.tolist ())  

Second, interceptors
1. What is an interceptor?

Interceptors, which are used in AOP (aspect-oriented programming) to intercept a method or field before it is accessed, and then add some action before or after it. Interception is an implementation strategy of AOP.
The Chinese document in WebWork is interpreted as--interceptors are objects that dynamically intercept action calls. It provides a mechanism to enable developers to define code that executes before and after an action executes, or to prevent it from executing before an action executes. It also provides a way to extract the reusable parts of an action.
When it comes to interceptors, there's one more word you should know-the interceptor chain (Interceptor Chain, called the Interceptor stack interceptor stack in struts 2). The Interceptor chain is a chain that binds the interceptor in a certain order. When accessing an intercepted method or field, interceptors in the interceptor chain are called in the order in which they were previously defined.

2. How to implement the Interceptor:

Most of the time, the Interceptor method is invoked in the form of proxies. The block implementation of Struts 2 is relatively straightforward. When the request arrives at the servletdispatcher of Struts 2, struts 2 looks for the configuration file, instantiates the relative interceptor object based on its configuration, and then strings it into a list, the last one to invoke the interceptor in the list.

3. Interceptor: Turn the water down and stop the fish! By the way, send a power:

4. Sample Code

How to define an interceptor in an XML file<Interceptors><Interceptor name="Filteripinterceptor" class="Com.xxxx.web.FilterIPActionInterceptor"/> <interceptor-stack name="Filteripstack" > <interceptor-ref name=" Defaultstack "/> <interceptor-ref name=" filteripinterceptor "  /> </ interceptor-stack></interceptors>         
How to write a custom interceptorPublicClassFilteripactioninterceptorExtendsabstractinterceptor{/** log control. */PrivateFinal log log = Logfactory.getlog (GetClass ());/** *@see Com.opensymphony.xwork2.interceptor.abstractinterceptor#intercept (com.opensymphony.xwork2.ActionInvocation ) */@Override@SuppressWarnings ("Unchecked")Public StringIntercept (actioninvocation invocation)Throws Exception {String result =NullGets the current method name. String methodName = Invocation.getinvocationcontext (). GetName (); String Currip =Nulltry {if (Invocation.getaction ()instanceof portletaction) {portletaction action = (portletaction) invocation.getaction (); Currip = Action.getRequest (). Getremoteaddr (); } String IP = Applicationresource.gethotvalue ("Allow_cache_ip");if (Stringutils.isblank (IP) | | Stringutils.isblank (Currip)) {Log.error ("Allow the refreshed IP to not exist or the currently requested IP is illegal.");ThrowNew Noallowipexception (); }else {string[] ips = Ip.split (","); Boolean errorip = true; For (String s:ips) { if (s.equals (currip)) Errorip = false;} //Judge IP if (errorip) throw new Noallowipexception ();} result = Invocation.invoke ();  Call the intercepted method} catch (Exception e) {log.error ("Exception class Name:" + invocation.getaction (). GetClass ()); Log.error ("Exception method:" + MethodName, E); throw e;} return result;}}                

Example2 User-aware link: https:www.zhihu.com/question/35225845/answer/61876681 Source: Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.ClassRiver {Flowint volume;Total number of fishint numfish;}ClassPowergenerator {Double Generate (int volume) {Assuming that every 100 cubic metre of soaked is electricallyReturn volume/100; }}InterfaceInterceptor {void intercept (river);}ClassSomeinterceptorImplementsInterceptor {Powergenerator generator =New Powergenerator (); @OverridePublicvoid Intercept (river) {Consumes 1000 cubic meters of water to generate electricity.int waterused =1000;The water volume was reduced by 1000. Please don't talk to me about the principle of hydropower station,I'm just a metaphor river.volume-= waterused;Power generation Generator.generate (waterused);Intercept all the fish river.numfish =0; }}ClassRivercontroller {Interceptor Interceptor;void Flow (river) {Source accumulated water and fish river.volume + =100000 river.numfish + = 1000 // Through the dam interceptor.intercept (river); //a little rain river.volume + = 1000} void Setinterceptor (Interceptor Interceptor) {this.interceptor = Interceptor}}class main {public Span class= "Hljs-keyword" >static void Main (String args[]) {Rivercontroller rc = new Rivercontroller; Interceptor inter = new someinterceptor (); //This step is often called control inversion or dependency injection, but there is nothing rc.setinterceptor (inter); Rc.flow ( new River ()); }} 

The difference between interceptors and filters:

 1. 拦截器是基于java的反射机制的,而过滤器是基于函数回调。 2. 拦截器不依赖与servlet容器,过滤器依赖与servlet容器。  3. 拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。 4. 拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。  5. 在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次拦截器的代      码实现。 6. Filter基于回调函数,我们需要实现的filter接口中doFilter方法就是回调函数,而interceptor则基于     java本身的反射机制,这是两者最本质的区别。 7. Filter是依赖于servlet容器的,即只能在servlet容器中执行,很显然没有servlet容器就无法来回调    doFilter方法。而interceptor与servlet容器无关。 8. Filter的过滤范围比Interceptor大,Filter除了过滤请求外通过通配符可以保护页面,图片,文件等等,    而Interceptor只能过滤请求。 9. Filter的过滤例外一般是在加载的时候在init方法声明,而Interceptor可以通过在xml声明是guest请求还    是user请求来辨别是否过滤。

third, the listener
1. Listener (Listener): When an event occurs, you want to get the details of the event, instead of interfering with the process of the event itself, it is necessary to use the listener.

2. Sample Code

User-aware Link: https:www.zhihu.com/question/35225845/answer/61876681 Source: Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.ListenerInterfaceBedlistener {The listener receives an event in the parameter, which is often read-onlyThe listener's method name usually begins with "on"void Onbedsound (String sound);}ClassNeighbor {Bedlistener listener;Still the so-called control reversal Setlistener (Bedlistener listener) {This.listener = listener;} void Dointerestingstuff () { ///According to local laws and regulations, part of the content cannot be displayed //The event is sent to the listener listener.onbedsound ("sex"); Listener.onbedsound ("Oyeah");}} class Main { public static void Main (String args[]) {Neighbor n = new Neighbor (); N.setlisten ER (sound and Generatepower ()); N.dointerestingstuff (); } private static void Generatepower () { //according to local laws and regulations, some content cannot be displayed}}     

The difference and use of Java Web Filter and Interceptor

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.