Dropwizard 为所有资源添加响应过滤器
Dropwizard Add Response Filter for All Resources
如何向我的 Dropwizard 应用程序添加一个过滤器来验证每个资源返回的响应?
我应该使用 javax.servlet.Filter
还是 javax.ws.rs.container.ContainerResponseFilter
任何与其用途相关的示例都将不胜感激。
我想你想用的是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。
要使用 dropwizard 为所有资源添加响应过滤器,您可以执行以下操作:
创建一个扩展 javax.servlet.Filter
-
的 CustomFilter
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() {
}
}
然后将相同的内容注册到扩展 Application
-
的 Service
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
过滤所有资源。
如何向我的 Dropwizard 应用程序添加一个过滤器来验证每个资源返回的响应?
我应该使用 javax.servlet.Filter
还是 javax.ws.rs.container.ContainerResponseFilter
任何与其用途相关的示例都将不胜感激。
我想你想用的是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。
要使用 dropwizard 为所有资源添加响应过滤器,您可以执行以下操作:
创建一个扩展
的 CustomFilterjavax.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() { } }
然后将相同的内容注册到扩展
的Application
-Service
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
过滤所有资源。