简体   繁体   English

如何在playframework中应用全局过滤器

[英]How to apply a global filter in playframework

When using @before, it is only used in one class. 使用@before时,它仅用于一个类。 How do I apply a global filter in playframework? 如何在playframework中应用全局过滤器? So that one filter is used for all controller classes. 因此,一个过滤器用于所有控制器类。

A simple solution is to extend a base controller for all of your controllers and have the @Before in the base controller. 一个简单的解决方案是为所有控制器扩展一个基本控制器,并在基本控制器中使用@Before。

The other option (and the better solution, as it is more flexible) is to use the @With annotation. 另一种选择(更好的解决方案,因为它更灵活)是使用@With注释。 The example on the play documentation is 播放文档中的示例是

Example: 例:

public class Secure extends Controller {

    @Before
    static void checkAuthenticated() {
        if(!session.containsKey("user")) {
            unAuthorized();
        }
    }
}    

And on another Controller: 在另一个控制器上:

@With(Secure.class)
public class Admin extends Application {

    ...

}

This means the Admin controller will process all the interceptors (@Before, @After, @Finally) contained within the Secure controller. 这意味着Admin控制器将处理Secure控制器中包含的所有拦截器(@ Before,@ After,@Finally)。

I did this very thing by handling incoming requests globally in the GlobalSettings class: 我通过在GlobalSettings类中全局处理传入的请求来做到这一点:

This describes the class: http://www.playframework.org/documentation/2.0/JavaGlobal 这描述了这个类: http//www.playframework.org/documentation/2.0/JavaGlobal

This describes the method you'd want to override. 这描述了您想要覆盖的方法。 http://www.playframework.org/documentation/2.0/JavaInterceptors http://www.playframework.org/documentation/2.0/JavaInterceptors

Here's an example of how I used it in my own project (of course, this is a simplified version of what you're looking for): 这是我在自己的项目中使用它的一个例子(当然,这是你正在寻找的简化版本):

@Override
public play.mvc.Action onRequest(play.mvc.Http.Request request, java.lang.reflect.Method method) {
    if (request.path().startsWith("/secret/locked")) {
        return new Action.Simple() {
            @Override
            public Result call(play.mvc.Http.Context ctx) throws Throwable {
                return redirect(routes.Application.forbidden());
            }
        };
    }

    return super.onRequest(request, method);
}

You can simply use PlayPlugin for this issue. 您可以简单地使用PlayPlugin来解决此问题。 See here for more details. 有关详细信息,请参见此处

It's not a good solution to extend a base controller for all of your controllers and have the @Before in the base controller. 扩展所有控制器的基本控制器并在基本控制器中使用@Before不是一个好的解决方案。

You can extends the filter or essensialfilter .eg 您可以扩展过滤器或essensialfilter .eg

class filter1 extends Filter {} class filter1 extends Filter {}

and apply filter1 to Global 并将filter1应用于Global

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM