下面列出了怎么用javax.servlet.annotation.WebServlet的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
default void add(Element element) {
// JAX-RS
ApplicationPath applicationPath = element.getAnnotation(ApplicationPath.class);
if (applicationPath != null) {
HashMap<String, Object> map = new HashMap<>();
map.put(ApplicationPath.class.getName(), new HashMap<String, String>() {{
put("value", applicationPath.value());
}});
addAnnotationConfiguration(map);
}
if (element.getAnnotation(Path.class) != null) {
addAnnotationConfiguration(Collections.emptyMap());
}
// servlet
if (element.getAnnotation(WebServlet.class) != null) {
addAnnotationConfiguration(Collections.emptyMap());
}
}
@Override
public void install(final Environment environment, final HttpServlet instance) {
final Class<? extends HttpServlet> extType = FeatureUtils.getInstanceClass(instance);
final WebServlet annotation = FeatureUtils.getAnnotation(extType, WebServlet.class);
final String[] patterns = annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value();
Preconditions.checkArgument(patterns.length > 0,
"Servlet %s not specified url pattern for mapping", extType.getName());
final AdminContext context = FeatureUtils.getAnnotation(extType, AdminContext.class);
final String name = WebUtils.getServletName(annotation, extType);
reporter.line("%-25s %-8s %-4s %s %s", Joiner.on(",").join(patterns),
WebUtils.getAsyncMarker(annotation), WebUtils.getContextMarkers(context),
RenderUtils.renderClassLine(extType), name);
if (WebUtils.isForMain(context)) {
configure(environment.servlets(), instance, extType, name, annotation);
}
if (WebUtils.isForAdmin(context)) {
configure(environment.admin(), instance, extType, name, annotation);
}
}
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 static boolean hasAsync(Servlet existing) {
boolean result = false;
Class<?> clazz = existing.getClass();
WebServlet ws = clazz.getAnnotation(WebServlet.class);
if (ws != null) {
result = ws.asyncSupported();
}
return result;
}
/**
* 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;
}
@Override
public void init(ServletContextHandler context) {
String pkgx = CoreConfig.getInstance("defines" )
.getProperty("apply.serv");
if ( pkgx != null ) {
String[] pkgs = pkgx.split(";");
for(String pkgn : pkgs) {
pkgn = pkgn.trim ( );
if ( pkgn.length( ) == 0 ) {
continue;
}
Set<String> clss = getClss(pkgn);
for(String clsn : clss) {
Class clso = getClso(clsn);
WebFilter wf = (WebFilter ) clso.getAnnotation(WebFilter.class );
if (null != wf) {
addFilter (context, clso, wf);
}
WebServlet wb = (WebServlet ) clso.getAnnotation(WebServlet.class );
if (null != wb) {
addServlet (context, clso, wb);
}
WebListener wl = (WebListener) clso.getAnnotation(WebListener.class);
if (null != wl) {
addListener(context, clso, wl);
}
}
}
}
}
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/**/);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void addServletWithMapping(ServletHandler sh, Class type){
WebServlet annotation = (WebServlet)type.getAnnotation(WebServlet.class);
String[] paths = annotation.value();
for (String path : paths) {
sh.addServletWithMapping(type, path);
}
}
@Override
public Collection<ClasspathScanRequest> classpathScanRequests() {
return classpathScanRequestBuilder()
.annotationType(WebFilter.class)
.annotationType(WebServlet.class)
.annotationType(WebListener.class)
.build();
}
@Override
public InitState initialize(InitContext initContext) {
if (servletContext != null) {
listenerDefinitions.addAll(
detectListeners(initContext.scannedClassesByAnnotationClass().get(WebListener.class)));
filterDefinitions.addAll(detectFilters(initContext.scannedClassesByAnnotationClass().get(WebFilter.class)));
servletDefinitions.addAll(
detectServlets(initContext.scannedClassesByAnnotationClass().get(WebServlet.class)));
}
return InitState.INITIALIZED;
}
@SuppressWarnings("unchecked")
private List<ServletDefinition> detectServlets(Collection<Class<?>> servletClasses) {
List<ServletDefinition> servletDefinitions = new ArrayList<>();
for (Class<?> candidate : servletClasses) {
if (Servlet.class.isAssignableFrom(candidate)) {
Class<? extends Servlet> servletClass = (Class<? extends Servlet>) candidate;
WebServlet annotation = servletClass.getAnnotation(WebServlet.class);
ServletDefinition servletDefinition = new ServletDefinition(
Strings.isNullOrEmpty(annotation.name()) ? servletClass.getCanonicalName() : annotation.name(),
servletClass
);
servletDefinition.setAsyncSupported(annotation.asyncSupported());
if (annotation.value().length > 0) {
servletDefinition.addMappings(annotation.value());
}
if (annotation.urlPatterns().length > 0) {
servletDefinition.addMappings(annotation.urlPatterns());
}
servletDefinition.setLoadOnStartup(annotation.loadOnStartup());
servletDefinition.addInitParameters(convert(annotation.initParams()));
servletDefinitions.add(servletDefinition);
}
}
return servletDefinitions;
}
private void procesServlets() {
Consumer<Class<? extends HttpServlet>> c = servlet -> {
WebServlet webServlet = ClassUtils.getAnnotation(servlet, WebServlet.class);
if(webServlet != null) {
ServletDescriptor servletDescriptor = new ServletDescriptor(webServlet.name(),
webServlet.value(), mapUrls(webServlet.urlPatterns()), webServlet.loadOnStartup(),
webServlet.initParams(),webServlet.asyncSupported(),servlet);
webServer.addServlet(servletDescriptor);
}
};
extension.processServlets(c);
}
private void addAnnotatedServlets(DeploymentInfo di, Archive<?> archive) {
Map<ArchivePath, Node> classNodes = archive.getContent((ArchivePath path) -> {
String stringPath = path.get();
return (stringPath.startsWith("/WEB-INF/classes") && stringPath.endsWith("class"));
});
for (Map.Entry<ArchivePath, Node> entry : classNodes.entrySet()) {
Node n = entry.getValue();
if (n.getAsset() instanceof ClassAsset) {
ClassAsset classAsset = (ClassAsset) n.getAsset();
Class<?> clazz = classAsset.getSource();
WebServlet annotation = clazz.getAnnotation(WebServlet.class);
if (annotation != null) {
ServletInfo undertowServlet = new ServletInfo(clazz.getSimpleName(), (Class<? extends Servlet>) clazz);
String[] mappings = annotation.value();
if (mappings != null) {
for (String urlPattern : mappings) {
undertowServlet.addMapping(urlPattern);
}
}
di.addServlet(undertowServlet);
}
}
}
}
@Override
protected void webConfig() {
if (context.getServletContext().getAttribute("meecrowave.configuration") == null) { // redeploy
context.getServletContext().setAttribute("meecrowave.configuration",
Meecrowave.Builder.class.isInstance(configuration) ? configuration : new Meecrowave.Builder(configuration));
context.addServletContainerInitializer(intializer, emptySet());
}
if (!configuration.isTomcatScanning()) {
super.webConfig();
return;
}
// eagerly start CDI to scan only once and not twice (tomcat+CDI)
final ClassLoader loader = context.getLoader().getClassLoader(); // should already be started at that point
final Thread thread = Thread.currentThread();
final ClassLoader old = thread.getContextClassLoader();
thread.setContextClassLoader(loader);
try {
final OWBTomcatWebScannerService scannerService = OWBTomcatWebScannerService.class.cast(WebBeansContext.getInstance().getScannerService());
scannerService.setFilter(ofNullable(context.getJarScanner()).map(JarScanner::getJarScanFilter).orElse(null), context.getServletContext());
scannerService.setDocBase(context.getDocBase());
scannerService.setShared(configuration.getSharedLibraries());
if (configuration.getWatcherBouncing() > 0) { // note that caching should be disabled with this config in most of the times
watcher = new ReloadOnChangeController(context, configuration.getWatcherBouncing());
scannerService.setFileVisitor(f -> watcher.register(f));
}
scannerService.scan();
finder = scannerService.getFinder();
finder.link();
final CdiArchive archive = CdiArchive.class.cast(finder.getArchive());
Stream.of(WebServlet.class, WebFilter.class, WebListener.class)
.forEach(marker -> finder.findAnnotatedClasses(marker).stream()
.filter(c -> !Modifier.isAbstract(c.getModifiers()) && Modifier.isPublic(c.getModifiers()))
.forEach(webComponent -> webClasses.computeIfAbsent(
archive.classesByUrl().entrySet().stream()
.filter(e -> e.getValue().getClassNames().contains(webComponent.getName()))
.findFirst().get().getKey(), k -> new HashSet<>())
.add(webComponent)));
} finally {
thread.setContextClassLoader(old);
}
try {
super.webConfig();
} finally {
webClasses.clear();
finder = null;
}
}
@Override
public void init() throws ServletException {
root = new Resource();
Method[] methods = getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
RequestMethod requestMethod = method.getAnnotation(RequestMethod.class);
if (requestMethod != null) {
Handler handler = new Handler(method);
Resource resource = root;
ResourcePath resourcePath = method.getAnnotation(ResourcePath.class);
if (resourcePath != null) {
String[] components = resourcePath.value().split("/");
for (int j = 0; j < components.length; j++) {
String component = components[j];
if (component.length() == 0) {
continue;
}
if (component.startsWith(ResourcePath.PATH_VARIABLE_PREFIX)) {
int k = ResourcePath.PATH_VARIABLE_PREFIX.length();
String key;
if (component.length() > k) {
if (component.charAt(k++) != ':') {
throw new ServletException("Invalid path variable.");
}
key = component.substring(k);
component = ResourcePath.PATH_VARIABLE_PREFIX;
} else {
key = null;
}
handler.keys.add(key);
}
Resource child = resource.resources.get(component);
if (child == null) {
child = new Resource();
resource.resources.put(component, child);
}
resource = child;
}
}
String verb = requestMethod.value().toLowerCase();
LinkedList<Handler> handlerList = resource.handlerMap.get(verb);
if (handlerList == null) {
handlerList = new LinkedList<>();
resource.handlerMap.put(verb, handlerList);
}
handlerList.add(handler);
}
}
Class<? extends WebService> type = getClass();
if (getClass().getAnnotation(WebServlet.class) != null) {
services.put(type, this);
}
}
@Override
public boolean matches(final Class<?> type) {
return FeatureUtils.is(type, HttpServlet.class)
&& FeatureUtils.hasAnnotation(type, WebServlet.class);
}
public void findServlets(@Observes @WithAnnotations({WebServlet.class})
ProcessAnnotatedType<? extends HttpServlet> pat) {
servlets.add(pat.getAnnotatedType().getJavaClass());
}
private void registerServlets(ServletHandler handler) {
Class[] classes = new Class[]{RootUIServlet.class, UIIconServlet.class};
for (Class aClass : classes) {
Servlet servlet = (Servlet)ReflectionUtil.newInstance(aClass);
ServletHolder servletHolder = new ServletHolder(servlet);
WebServlet declaredAnnotation = (WebServlet)aClass.getDeclaredAnnotation(WebServlet.class);
String[] urls = declaredAnnotation.urlPatterns();
for (String url : urls) {
handler.addServletWithMapping(servletHolder, url);
}
System.out.println(aClass.getName() + " registered to: " + Arrays.asList(urls));
}
}
/**
* @param servlet servlet annotation
* @param type servlet type
* @return servlet name or generated name if name not provided
*/
public static String getServletName(final WebServlet servlet, final Class<? extends HttpServlet> type) {
final String name = Strings.emptyToNull(servlet.name());
return name != null ? name : generateName(type, "servlet");
}
/**
* @param annotation servlet registration annotation
* @return "async" string if servlet support async and empty string otherwise
*/
public static String getAsyncMarker(final WebServlet annotation) {
return getAsyncMarker(annotation.asyncSupported());
}