本文整理汇总了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;
}
示例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();
}
示例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() {
}
});
}
示例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());
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
示例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);
}
}
示例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);
}
}
示例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;
}
示例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);
}
}
示例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}");
}
示例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}");
}
示例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;
}