Servlet3.0开始引入annotation用于部署,

  • @WebServlet用于定义servlet,
  • @WebListener用于定义监听器(对于不同类型的监听器又有细分),
  • @WebFilter用于定义过滤器,
  • @initParams用于定义初始化参数,
  • ……

这里给出一个使用@WebServlet的例子,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.IOException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/annotation.do", initParams = {
@WebInitParam(name = "newPattern", value = "annotation"),
@WebInitParam(name = "oldPattern", value = "web.xml") })
public class CoreServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html");
response.getWriter().print(
"Using " + getServletConfig().getInitParameter("newPattern")
+ " not "
+ getServletConfig().getInitParameter("oldPattern"));
}
}

访问...\annotation.do,可以看到

Using annotation not web.xml

如果同时存在web.xml和注解,web.xml中指定的内容拥有更高的优先级。

前面@WebServlet指定了me.annotation.web.CoreServlet/annotation.do的映射关系,相当于在web.xml中添加,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<servlet>
<servlet-name>me.annotation.web.CoreServlet</servlet-name>
<servlet-class>me.annotation.web.CoreServlet</servlet-class>
<init-param>
<param-value>newPattern</param-value>
<param-name>annotation</param-name>
</init-param>
<init-param>
<param-value>oldPattern</param-value>
<param-name>web.xml</param-name>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>me.annotation.web.CoreServlet</servlet-name>
<url-pattern>/annotation.do</url-pattern>
</servlet-mapping>

<servlet-name>值不同认定为不同的映射关系。

可以在web.xml添加

1
<metadata-complete>true</metadata-complete>

禁用注解,缺省或值为false即可以使用注解。

参考资料:

JSR 340: Java Servlet 3.1 Specification

Package javax.servlet.annotation