我最終創建了一個方法addPublicFilter()
,它將過濾器PublicFilter
應用於您作爲參數傳遞的路徑和方法。
public class PublicFilter implements Filter {
private FilterConfig filterConfig;
public static final String PUBLIC_METHODS = "com.example.access.PUBLIC_METHODS";
static final String IS_PUBLIC = "com.example.access.IS_PUBLIC";
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final List<String> allowedMethods = Arrays.asList(filterConfig.getInitParameter(PUBLIC_METHODS).split(","));
final String method = ((HttpServletRequest) request).getMethod();
if (allowedMethods.contains(method)) request.setAttribute(IS_PUBLIC, true);
chain.doFilter(request, response);
}
public void destroy() {}
}
然後在碼頭我的方法:
private static void addPublicFilter(ServletContextHandler context, String path, String publicMethods) {
final FilterHolder holder = new FilterHolder(PublicFilter.class);
holder.setInitParameter(PublicFilter.PUBLIC_METHODS, publicMethods);
context.addFilter(holder, path, EnumSet.of(DispatcherType.REQUEST));
}
,我把它叫做:
addPublicFilter(context, "/*", "OPTIONS");
addPublicFilter(context, "/user/*", "POST");
addPublicFilter(context, "/session", "POST,GET");
我不明白它是如何可能增加一個過濾器(包過濾器),以一個特定的servlet傳遞一個字符串來描述該特定servlet中的哪些方法應該被認證。那是你的想法吧? FilterConfig可能? – niklabaz
我正在遠離XML,並且以編程方式將過濾器添加到上下文中。 – niklabaz