如何在我的 Dropwizard 应用程序中添加一个过滤器,以验证每个资源返回的响应?
我应该使用javax.servlet.Filter
还是javax.ws.rs.container.ContainerResponseFilter
任何与其用途相关的例子都将受到赞赏。
答案 0 :(得分:4)
要使用dropwizard为所有资源添加响应过滤器,您可以执行以下操作:
创建一个扩展url
-
javax.servlet.Filter
然后将其注册到public class CustomFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// your filtering task
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
扩展Service
-
Application
public class CustomService extends Application<CustomConfig> { //CustomConfig extend 'io.dropwizard.Configuration'
public static void main(String[] args) throws Exception {
new CustomService().run(args);
}
@Override
public void initialize(Bootstrap<CustomConfig> someConfigBootstrap) {
// do some initialization
}
@Override
public void run(CustomConfig config, io.dropwizard.setup.Environment environment) throws Exception {
... // resource registration
environment.servlets().addFilter("Custom-Filter", CustomFilter.class)
.addMappingForUrlPatterns(java.util.EnumSet.allOf(javax.servlet.DispatcherType.class), true, "/*");
}
}
现在,您应该使用上面定义的CustomFilter
过滤所有资源。
答案 1 :(得分:1)
我认为你想要使用的是javax.servlet.Filter
。
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.
更多信息here。