下面列出了怎么用javax.servlet.annotation.WebInitParam的API类实例代码及写法,或者点击链接到github查看源代码。
private void addFilter(ServletContextHandler context, Class clso, WebFilter anno) {
DispatcherType[] ds = anno.dispatcherTypes( );
List <DispatcherType> ls = Arrays .asList(ds);
EnumSet<DispatcherType> es = EnumSet.copyOf(ls);
FilterHolder hd = new FilterHolder (clso );
hd.setName (anno.filterName( ));
hd.setAsyncSupported(anno.asyncSupported());
for(WebInitParam nv : anno.initParams ()) {
hd.setInitParameter(nv.name( ), nv.value());
}
for(String ur : anno.urlPatterns()) {
context.addFilter (hd, ur, es);
}
}
private void configure(final ServletEnvironment environment, final HttpServlet servlet,
final Class<? extends HttpServlet> type, final String name, final WebServlet annotation) {
final ServletRegistration.Dynamic mapping = environment.addServlet(name, servlet);
final Set<String> clash = mapping
.addMapping(annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value());
if (clash != null && !clash.isEmpty()) {
final String msg = String.format(
"Servlet registration %s clash with already installed servlets on paths: %s",
type.getSimpleName(), Joiner.on(',').join(clash));
if (option(DenyServletRegistrationWithClash)) {
throw new IllegalStateException(msg);
} else {
logger.warn(msg);
}
}
if (annotation.initParams().length > 0) {
for (WebInitParam param : annotation.initParams()) {
mapping.setInitParameter(param.name(), param.value());
}
}
mapping.setAsyncSupported(annotation.asyncSupported());
}
private void configure(final ServletEnvironment environment, final Filter filter,
final String name, final WebFilter annotation) {
final FilterRegistration.Dynamic mapping = environment.addFilter(name, filter);
final EnumSet<DispatcherType> dispatcherTypes = EnumSet.copyOf(Arrays.asList(annotation.dispatcherTypes()));
if (annotation.servletNames().length > 0) {
mapping.addMappingForServletNames(dispatcherTypes, false, annotation.servletNames());
} else {
final String[] urlPatterns = annotation.urlPatterns().length > 0
? annotation.urlPatterns() : annotation.value();
mapping.addMappingForUrlPatterns(dispatcherTypes, false, urlPatterns);
}
if (annotation.initParams().length > 0) {
for (WebInitParam param : annotation.initParams()) {
mapping.setInitParameter(param.name(), param.value());
}
}
mapping.setAsyncSupported(annotation.asyncSupported());
}
@Test
public void testConversion() {
Class<? extends HttpServlet> servletClass = DefaultServlet.class;
String name = "name";
String[] value = new String[]{"a"};
String[] urlPatterns = new String[]{"/b"};
int loadOnStartup = 2;
WebInitParam[] initParams = new WebInitParam[]{new WebParam("name","value")};
boolean asyncSupported = true;
ServletDescriptor servletDescriptor = new ServletDescriptor(name, value, urlPatterns, loadOnStartup,
initParams, asyncSupported, servletClass);
ServletInfo servletInfo = mapper.apply(servletDescriptor);
assertThat(servletInfo.getName()).isEqualTo(name);
assertThat(servletInfo.getServletClass()).isEqualTo(servletClass);
assertThat(servletInfo.getMappings()).isEqualTo(asList(urlPatterns));
assertThat(servletInfo.getLoadOnStartup()).isEqualTo(loadOnStartup);
assertThat(servletInfo.isAsyncSupported()).isEqualTo(asyncSupported);
assertThat(servletInfo.getInitParams()).isEqualTo(singletonMap("name","value"));
}
/**
* Is this a web annotation.
*
* @param annotation the annotation.
* @return true if it is, false otherwise.
*/
private boolean isWebAnnotation(Annotation annotation) {
return annotation instanceof WebServlet
|| annotation instanceof WebListener
|| annotation instanceof WebInitParam
|| annotation instanceof WebFilter
|| annotation instanceof ServletSecurity
|| annotation instanceof MultipartConfig;
}
private Map<String, String> readAnnotatedInitParams() {
Map<String, String> initParams = new HashMap<>();
if (isAnnotated()) {
WebFilter regAnnotation = filter.getClass().getAnnotation(WebFilter.class);
for (WebInitParam param : regAnnotation.initParams()) {
initParams.put(param.name(), param.value());
}
}
return initParams;
}
private void addServlet(ServletContextHandler context, Class clso, WebServlet anno) {
ServletHolder hd = new ServletHolder(clso );
hd.setName (anno./****/name( ));
hd.setAsyncSupported(anno.asyncSupported());
for(WebInitParam nv : anno.initParams ()) {
hd.setInitParameter(nv.name( ), nv.value());
}
for(String ur : anno.urlPatterns()) {
context.addServlet(hd, ur/**/);
}
}
private Map<String, String> convert(WebInitParam[] webInitParams) {
Map<String, String> map = new HashMap<>();
for (WebInitParam webInitParam : webInitParams) {
map.put(webInitParam.name(), webInitParam.value());
}
return map;
}
@Produces
@Dependent
public ServletDescriptor cxfServlet(RestServerConfiguration restServerConfiguration) {
String servletMapping = restServerConfiguration.getRestServletMapping();
List<WebInitParam> params = new ArrayList<>();
if(enableSseTransport) {
params.add(new WebParam(CXFNonSpringJaxrsServlet.TRANSPORT_ID, SseHttpTransportFactory.TRANSPORT_ID));
}
WebInitParam[] initParams = params.toArray(new WebInitParam[params.size()]);
return new ServletDescriptor("CXF",null, new String[]{servletMapping},1, initParams,true,CXFCdiServlet.class);
}
@Produces
public ServletDescriptor resteasyServlet() {
String path = restServerConfiguration.getRestServerUri();
if( !(applicationInstance.isUnsatisfied() || applicationInstance.isAmbiguous())) {
ApplicationPath appPath = ClassUtils.getAnnotation(applicationInstance.get().getClass(), ApplicationPath.class);
if(appPath != null) {
path = appPath.value();
}
}
String pattern = path.endsWith("/") ? path + "*" : path + "/*";
WebInitParam param = new WebParam("resteasy.servlet.mapping.prefix", path);
return new ServletDescriptor("ResteasyServlet",new String[]{pattern}, new String[]{pattern},
1,new WebInitParam[]{param},true,HttpServlet30Dispatcher.class);
}
@Test
public void shouldCreateServletHolderWithParams() {
when(servletHandler.newServletHolder(Source.EMBEDDED)).thenReturn(new ServletHolder(Source.EMBEDDED));
ServletDescriptor servletDescriptor = new ServletDescriptor("name", new String[]{"uri"}, new String[]{"uri"},
1,new WebInitParam[]{new WebParam("key","value")},true, DefaultServlet.class);
ServletHolder holder = mapper.apply(servletDescriptor);
assertThat(holder.getInitParameters()).isEqualTo(singletonMap("key","value"));
}
@Produces
public ServletDescriptor swaggerUIDispatcherServlet() {
String name = SwaggerUIDispatcherServlet.class.getSimpleName();
String[] uris = new String[] { config.getSwaggerUIPath(), config.getSwaggerUIPath() + UI_MATCH_FORWARD };
WebInitParam[] params = null;
return new ServletDescriptor(name, uris, uris, 1, params, false, SwaggerUIDispatcherServlet.class);
}
@Override
public ServletInfo apply(ServletDescriptor servletDescriptor) {
ServletInfo servletInfo = Servlets.servlet(servletDescriptor.name(), servletDescriptor.servletClass())
.setAsyncSupported(servletDescriptor.asyncSupported())
.setLoadOnStartup(servletDescriptor.loadOnStartup())
.addMappings(servletDescriptor.urlPatterns());
if(servletDescriptor.initParams() != null) {
for(WebInitParam param : servletDescriptor.initParams()) {
servletInfo.addInitParam(param.name(), param.value());
}
}
return servletInfo;
}
public FilterDescriptor(String name, String[] value, String[] urlPatterns, DispatcherType[] dispatcherTypes,
WebInitParam[] initParams, boolean asyncSupported, String[] servletNames, Class<? extends Filter> clazz) {
this.name = name;
this.value = value;
this.urlPatterns = urlPatterns;
this.dispatcherTypes = dispatcherTypes;
this.initParams = initParams;
this.asyncSupported = asyncSupported;
this.servletNames = servletNames;
this.clazz = clazz;
}
public ServletDescriptor(String name, String[] value, String[] urlPatterns, int loadOnStartup, WebInitParam[] initParams,
boolean asyncSupported, Class<? extends HttpServlet> servletClass) {
this.name = name;
this.value = value;
this.urlPatterns = urlPatterns;
this.loadOnStartup = loadOnStartup;
this.initParams = initParams;
this.asyncSupported = asyncSupported;
this.servletClass = servletClass;
}
@Override
public void start() {
DeploymentInfo di = new DeploymentInfo()
.setContextPath("/")
.setDeploymentName("Undertow")
.setResourceManager(new ClassPathResourceManager(getClass().getClassLoader()))
.setClassLoader(ClassLoader.getSystemClassLoader());
super.getListeners().forEach(c ->di.addListener(listener(c)));
Collection<Class<?>> endpoints = extension.getEndpointClasses();
if(!endpoints.isEmpty()) {
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
endpoints.forEach(webSocketDeploymentInfo::addEndpoint);
di.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo);
}
getServletContextAttributes().forEach(di::addServletContextAttribute);
servlets.forEach(di::addServlet);
getFilterDescriptors().forEach(filterDescriptor -> {
FilterInfo filterInfo = filter(filterDescriptor.displayName(), filterDescriptor.getClazz()).setAsyncSupported(filterDescriptor.asyncSupported());
if(filterDescriptor.initParams() != null) {
for (WebInitParam param : filterDescriptor.initParams()) {
filterInfo.addInitParam(param.name(), param.value());
}
}
di.addFilter(filterInfo);
for(String url : filterDescriptor.urlPatterns()) {
for(DispatcherType dispatcherType : filterDescriptor.dispatcherTypes()) {
di.addFilterUrlMapping(filterDescriptor.displayName(), url, dispatcherType);
}
}
});
getInitParams().forEach(di::addInitParameter);
DeploymentManager deploymentManager = Servlets.defaultContainer().addDeployment(di);
deploymentManager.deploy();
try {
HttpHandler servletHandler = deploymentManager.start();
PathHandler path = path(Handlers.redirect("/"))
.addPrefixPath("/", servletHandler);
Builder undertowBuilder = Undertow.builder()
.addHttpListener(webServerConfiguration.getPort(), webServerConfiguration.getAddress())
.setHandler(path);
if (hammockRuntime.isSecuredConfigured()){
KeyManager[] keyManagers = loadKeyManager();
TrustManager[] trustManagers = loadTrustManager();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
undertowBuilder = undertowBuilder.addHttpsListener(webServerConfiguration.getSecuredPort(), webServerConfiguration.getAddress(), sslContext);
}
this.undertow = undertowBuilder.build();
this.undertow.start();
} catch (ServletException | GeneralSecurityException | IOException e) {
throw new RuntimeException("Unable to start server", e);
}
}
@Produces
public ServletDescriptor metricsServlet() {
String[] uris = new String[]{metricsConfig.getBaseUri()};
WebInitParam[] params = null;
return new ServletDescriptor("Metrics", uris, uris, 1, params, false, AdminServlet.class);
}
@Override
public WebInitParam[] initParams() {
return initParams;
}
@Override
public WebInitParam[] initParams() {
return initParams;
}