3

サーブレット 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 ファイルを定義します。

<?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.* など) に制限する方法はありますか?

4

1 に答える 1

1

これは Web コンテナによって異なります。たとえば、Tomcat では、catalina.properties で次の設定を使用できます (catalina.properties からコメントをコピーしました)。

# 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=
于 2013-03-19T14:30:57.237 に答える