【问题标题】:Servlet 3.0, limit the scan of WebServlet annotations to a given packageServlet 3.0,将 WebServlet 注释的扫描限制到给定的包
【发布时间】:2012-08-21 00:36:17
【问题描述】:

使用 Servlet 3.0, http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebServlet.html

我们可以定义一个带有 WebServlet 注解的类:

package com.example;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet({"/hello"})
public class HelloServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    response.getWriter().println("hello world");
  }
}

并定义一个 web.xml 文件而不映射 servlet:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
</web-app>

因此,对http://test.com/hello 的请求将正确打印“hello world”。

这是因为 Servlet 3.0 会扫描所有类以查找 WebServlet 注释。

有没有办法将此扫描限制在给定包中的类(例如,com.example.*)?

【问题讨论】:

    标签: servlet-3.0


    【解决方案1】:

    这取决于您的 Web 容器。例如,在 Tomcat 中,您可以在 catalina.properties 中使用以下设置(我从 catalina.properties 复制了 cmets):

    # List of JAR files that should not be scanned using the JarScanner
    # functionality. This is typically used to scan JARs for configuration
    # information. JARs that do not contain such information may be excluded from
    # the scan to speed up the scanning process. This is the default list. JARs on
    # this list are excluded from all scans. Scan specific lists (to exclude JARs
    # from individual scans) follow this. The list must be a comma separated list of
    # JAR file names.
    # The JARs listed below include:
    # - Tomcat Bootstrap JARs
    # - Tomcat API JARs
    # - Catalina JARs
    # - Jasper JARs
    # - Tomcat JARs
    # - Common non-Tomcat JARs
    tomcat.util.scan.DefaultJarScanner.jarsToSkip=\
    bootstrap.jar,commons-daemon.jar,tomcat-juli.jar,\
    annotations-api.jar,el-api.jar,jsp-api.jar,servlet-api.jar
    
    # Additional JARs (over and above the default JARs listed above) to skip when
    # scanning for Servlet 3.0 pluggability features. These features include web
    # fragments, annotations, SCIs and classes that match @HandlesTypes. The list
    # must be a comma separated list of JAR file names.
    org.apache.catalina.startup.ContextConfig.jarsToSkip=
    
    # Additional JARs (over and above the default JARs listed above) to skip when
    # scanning for TLDs. The list must be a comma separated list of JAR file names.
    org.apache.catalina.startup.TldConfig.jarsToSkip=
    

    【讨论】:

      猜你喜欢
      • 2015-01-10
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多