当前位置: 首页>>代码示例>>Java>>正文


Java Filter类代码示例

本文整理汇总了Java中javax.servlet.Filter的典型用法代码示例。如果您正苦于以下问题:Java Filter类的具体用法?Java Filter怎么用?Java Filter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Filter类属于javax.servlet包,在下文中一共展示了Filter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: general

import javax.servlet.Filter; //导入依赖的package包/类
public static Filter general(AuthorizationCodeResourceDetails client, ResourceServerProperties resourceServerProperties, String path, OAuth2ClientContext oauth2ClientContext) {
	OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(path){
		protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
		                                        FilterChain chain, Authentication authResult) throws IOException, ServletException {
			super.successfulAuthentication(request, response, chain, authResult);
			OAuth2AccessToken accessToken = restTemplate.getAccessToken();
			log.warn(new Gson().toJson(authResult));
			log.warn(new Gson().toJson(accessToken));
		}
	};
	OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client, oauth2ClientContext);
	oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
	UserInfoTokenServices tokenServices = new UserInfoTokenServices(resourceServerProperties.getUserInfoUri(), client.getClientId());
	tokenServices.setRestTemplate(oAuth2RestTemplate);
	oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
	return oAuth2ClientAuthenticationFilter;
}
 
开发者ID:DataAgg,项目名称:DAFramework,代码行数:18,代码来源:OAuth2Util.java

示例2: testMissingHostname

import javax.servlet.Filter; //导入依赖的package包/类
@Test
public void testMissingHostname() throws Exception {
  ServletRequest request = Mockito.mock(ServletRequest.class);
  Mockito.when(request.getRemoteAddr()).thenReturn(null);

  ServletResponse response = Mockito.mock(ServletResponse.class);

  final AtomicBoolean invoked = new AtomicBoolean();

  FilterChain chain = new FilterChain() {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
      throws IOException, ServletException {
      assertTrue(HostnameFilter.get().contains("???"));
      invoked.set(true);
    }
  };

  Filter filter = new HostnameFilter();
  filter.init(null);
  assertNull(HostnameFilter.get());
  filter.doFilter(request, response, chain);
  assertTrue(invoked.get());
  assertNull(HostnameFilter.get());
  filter.destroy();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:27,代码来源:TestHostnameFilter.java

示例3: correlationIdFilter

import javax.servlet.Filter; //导入依赖的package包/类
@Bean
public FilterRegistrationBean correlationIdFilter() {
    return new FilterRegistrationBean(new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
        }
    });
}
 
开发者ID:voyages-sncf-technologies,项目名称:cerebro,代码行数:19,代码来源:App.java

示例4: start

import javax.servlet.Filter; //导入依赖的package包/类
@Override
public void start(BundleContext context) throws Exception {
    log.info("######################################################");
    log.info("start");
    log.info("######################################################");

    Hashtable<String, String> props = new Hashtable<>();
    props.put("osgi.http.whiteboard.servlet.pattern", "/*");
    props.put("init.message", "Crazy filter!");
    props.put("service.ranking", "1");
    serviceRegistration = context.registerService(Filter.class.getName(), new CrazyFilter(), props);

    final ServiceReference<?> httpRef = context.getServiceReference("org.osgi.service.http.HttpService");
    httpService = (HttpService) context.getService(httpRef);

    httpService.registerServlet("/foo", new FooServlet(), new Hashtable(), httpService.createDefaultHttpContext());
}
 
开发者ID:L7R7,项目名称:magic-bundle,代码行数:18,代码来源:Activator.java

示例5: shiroFilterFactoryBean

import javax.servlet.Filter; //导入依赖的package包/类
/**
 * 对过滤器进行调整
 *
 * @param securityManager
 * @return
 */
@Bean(name = "shiroFilter")
protected ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager, Config config) {
    ShiroFilterFactoryBean filterFactoryBean = super.shiroFilterFactoryBean();
    filterFactoryBean.setSecurityManager(securityManager);
    
    //过滤器设置
    Map<String, Filter> filters = new HashMap<>();
    SecurityFilter securityFilter = new SecurityFilter();
    securityFilter.setClients("cas,rest,jwt");
    securityFilter.setConfig(config);
    filters.put("casSecurityFilter", securityFilter);
    
    CallbackFilter callbackFilter = new CallbackFilter();
    callbackFilter.setConfig(config);
    filters.put("callbackFilter", callbackFilter);
    
    filterFactoryBean.setFilters(filters);
    

    return filterFactoryBean;
}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:28,代码来源:ShiroConfiguration.java

示例6: fireInstanceEvent

import javax.servlet.Filter; //导入依赖的package包/类
/**
 * Notify all lifecycle event listeners that a particular event has
 * occurred for this Container.  The default implementation performs
 * this notification synchronously using the calling thread.
 *
 * @param type Event type
 * @param filter The relevant Filter for this event
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 */
public void fireInstanceEvent(String type, Filter filter,
                              ServletRequest request,
                              ServletResponse response) {

    if (listeners.length == 0)
        return;

    InstanceEvent event = new InstanceEvent(wrapper, filter, type,
                                            request, response);
    InstanceListener interested[] = null;
    synchronized (listeners) {
        interested = (InstanceListener[]) listeners.clone();
    }
    for (int i = 0; i < interested.length; i++)
        interested[i].instanceEvent(event);

}
 
开发者ID:c-rainstorm,项目名称:jerrydog,代码行数:28,代码来源:InstanceSupport.java

示例7: doFilter

import javax.servlet.Filter; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	// Lazily initialize the delegate if necessary.
	Filter delegateToUse = this.delegate;
	if (delegateToUse == null) {
		synchronized (this.delegateMonitor) {
			if (this.delegate == null) {
				WebApplicationContext wac = findWebApplicationContext();
				if (wac == null) {
					throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
				}
				this.delegate = initDelegate(wac);
			}
			delegateToUse = this.delegate;
		}
	}

	// Let the delegate perform the actual doFilter operation.
	invokeDelegate(delegateToUse, request, response, filterChain);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:DelegatingFilterProxy.java

示例8: doAsPrivilege

import javax.servlet.Filter; //导入依赖的package包/类
/**
 * Perform work as a particular <code>Subject</code>. Here the work will be
 * granted to a <code>null</code> subject.
 *
 * @param methodName
 *            the method to apply the security restriction
 * @param targetObject
 *            the <code>Filter</code> on which the method will be called.
 * @param targetParameterTypes
 *            <code>Class</code> array used to instantiate a
 *            <code>Method</code> object.
 * @param targetParameterValues
 *            <code>Object</code> array contains the runtime parameters
 *            instance.
 * @param principal
 *            the <code>Principal</code> to which the security privilege
 *            apply
 */
public static void doAsPrivilege(final String methodName, final Filter targetObject,
		final Class<?>[] targetParameterTypes, final Object[] targetParameterValues, Principal principal)
		throws java.lang.Exception {

	// CometFilter instances must not be cached as Filter or
	// NoSuchMethodException will be thrown.
	Class<? extends Filter> targetType = targetObject instanceof CometFilter ? CometFilter.class : Filter.class;

	Method method = null;
	Method[] methodsCache = classCache.get(Filter.class);
	if (methodsCache == null) {
		method = createMethodAndCacheIt(methodsCache, targetType, methodName, targetParameterTypes);
	} else {
		method = findMethod(methodsCache, methodName);
		if (method == null) {
			method = createMethodAndCacheIt(methodsCache, targetType, methodName, targetParameterTypes);
		}
	}

	execute(method, targetObject, targetParameterValues, principal);
}
 
开发者ID:how2j,项目名称:lazycat,代码行数:40,代码来源:SecurityUtil.java

示例9: test

import javax.servlet.Filter; //导入依赖的package包/类
private void test(String method, String operation, String contentType,
                  boolean upload, boolean error) throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.reset(request);
  Mockito.when(request.getMethod()).thenReturn(method);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_PARAM)).thenReturn(operation);
  Mockito.when(request.getParameter(HttpFSParametersProvider.DataParam.NAME)).
    thenReturn(Boolean.toString(upload));
  Mockito.when(request.getContentType()).thenReturn(contentType);

  FilterChain chain = Mockito.mock(FilterChain.class);

  Filter filter = new CheckUploadContentTypeFilter();

  filter.doFilter(request, response, chain);

  if (error) {
    Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),
                                       Mockito.contains("Data upload"));
  }
  else {
    Mockito.verify(chain).doFilter(request, response);
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:26,代码来源:TestCheckUploadContentTypeFilter.java

示例10: FilterInfo

import javax.servlet.Filter; //导入依赖的package包/类
public FilterInfo(final String name, final Class<? extends Filter> filterClass) {
    if (name == null) {
        throw UndertowServletMessages.MESSAGES.paramCannotBeNull("name");
    }
    if (filterClass == null) {
        throw UndertowServletMessages.MESSAGES.paramCannotBeNull("filterClass", "Filter", name);
    }
    if (!Filter.class.isAssignableFrom(filterClass)) {
        throw UndertowServletMessages.MESSAGES.filterMustImplementFilter(name, filterClass);
    }
    try {
        final Constructor<Filter> ctor = (Constructor<Filter>) filterClass.getDeclaredConstructor();
        ctor.setAccessible(true);
        this.instanceFactory = new ConstructorInstanceFactory<>(ctor);
        this.name = name;
        this.filterClass = filterClass;
    } catch (NoSuchMethodException e) {
        throw UndertowServletMessages.MESSAGES.componentMustHaveDefaultConstructor("Filter", filterClass);
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:21,代码来源:FilterInfo.java

示例11: ssoFilter

import javax.servlet.Filter; //导入依赖的package包/类
@Bean
public Filter ssoFilter(ClientResources client, String path) {
    MappingJackson2HttpMessageConverter customJsonMessageConverter = new
            MappingJackson2HttpMessageConverter();
    customJsonMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN));
    MyOAuth2ClientAuthenticationProcessingFilter filter = new MyOAuth2ClientAuthenticationProcessingFilter(path);
    filter.setAllowSessionCreation(true);
    MyOAuth2RestTemplate template = new MyOAuth2RestTemplate(client.getClient(), oauth2ClientContext);
    template.setMessageConverters(Arrays.asList(customJsonMessageConverter));
    filter.setRestTemplate(template);
    MyUserInfoTokenServices tokenServices = new MyUserInfoTokenServices(client.getResource().getUserInfoUri(),
            client.getClient().getClientId(),
            userService,
            userWechatService,
            userPrivilegeService,
            privilegeConfigService);
    tokenServices.setRestTemplate(template);
    filter.setTokenServices(tokenServices);
    return filter;
}
 
开发者ID:luotuo,项目名称:springboot-security-wechat,代码行数:21,代码来源:SecurityConfig.java

示例12: doPrivileged

import javax.servlet.Filter; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked") // doPrivileged() returns the correct type
public <T extends Filter> T createFilter(Class<T> c) throws ServletException {
	if (SecurityUtil.isPackageProtectionEnabled()) {
		try {
			return (T) invokeMethod(context, "createFilter", new Object[] { c });
		} catch (Throwable t) {
			ExceptionUtils.handleThrowable(t);
			if (t instanceof ServletException) {
				throw (ServletException) t;
			}
			return null;
		}
	} else {
		return context.createFilter(c);
	}
}
 
开发者ID:how2j,项目名称:lazycat,代码行数:18,代码来源:ApplicationContextFacade.java

示例13: before

import javax.servlet.Filter; //导入依赖的package包/类
@Override
protected void before() throws Throwable {
	originalConfigLocation = System.getProperty("spring.config.location");
	if (!StringUtils.isEmpty(configurationLocation)) {
		System.setProperty("spring.config.location", configurationLocation);
	}

	app = new SpringApplication(LocalTestDataFlowServer.class);
	configurableApplicationContext = (WebApplicationContext) app.run(new String[]{"--server.port=0"});

	Collection<Filter> filters = configurableApplicationContext.getBeansOfType(Filter.class).values();
	mockMvc = MockMvcBuilders.webAppContextSetup(configurableApplicationContext)
			.addFilters(filters.toArray(new Filter[filters.size()]))
			.build();
	dataflowPort = configurableApplicationContext.getEnvironment().resolvePlaceholders("${server.port}");
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-dashboard,代码行数:17,代码来源:LocalDataflowResource.java

示例14: before

import javax.servlet.Filter; //导入依赖的package包/类
@Override
protected void before() throws Throwable {

	final SpringApplicationBuilder builder = new SpringApplicationBuilder(LocalTestSkipperServer.class);

	if (this.configLocations  != null && this.configLocations.length > 0) {
		builder.properties(
			String.format("spring.config.location:%s", StringUtils.arrayToCommaDelimitedString(this.configLocations))
		);
	}

	if (this.configNames  != null && this.configNames.length > 0) {
		builder.properties(
			String.format("spring.config.name:%s", StringUtils.arrayToCommaDelimitedString(this.configNames))
		);
	}

	this.app = builder.build();



	configurableApplicationContext = app.run(
		new String[] { "--server.port=0" });

	Collection<Filter> filters = configurableApplicationContext.getBeansOfType(Filter.class).values();
	mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) configurableApplicationContext)
			.addFilters(filters.toArray(new Filter[filters.size()])).build();
	skipperPort = configurableApplicationContext.getEnvironment().resolvePlaceholders("${server.port}");
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-skipper,代码行数:30,代码来源:LocalSkipperResource.java

示例15: shiroFilterFactoryBean

import javax.servlet.Filter; //导入依赖的package包/类
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager, CasConfig casConfig, CasFilter casFilter){
	ShiroFilterFactoryBean factoryBean = new MyShiroFilterFactoryBean();
	factoryBean.setSecurityManager(securityManager);
	factoryBean.setLoginUrl(casConfig.getLocalServerLoginUrl());
	factoryBean.setSuccessUrl("/user");
	factoryBean.setUnauthorizedUrl("/403");
	// 添加casFilter到shiroFilter中
	Map<String, Filter> filterMap = new HashMap<String, Filter>(1);
	filterMap.put(CAS_FILTER, casFilter);
	factoryBean.setFilters(filterMap);

	loadShiroFilterChain(factoryBean, casConfig);
	return factoryBean;
}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:16,代码来源:ShiroCasConfig.java


注:本文中的javax.servlet.Filter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。