注册Servlet的两种方式

0. 问题

1. 配置web.xml

<servlet>
  <servlet-name>servletTest</servlet-name>
  <servlet-class>xxx</servlet-class>
  <init-param>
    <param-name>name</param-name>
    <param-value>peter</param-value>
  </init-param>
  <init-param>
    <param-name>age</param-name>
    <param-value>18</param-value>
  </init-param>
  <init-param>
    <param-name>room</param-name>
    <param-value>511</param-value>
  </init-param>
</servlet>
<servlet-mapping>
  <servlet-name>servletTest</servlet-name>
  <url-pattern>/student/getinfo</url-pattern>
  <url-pattern>/stu/*</url-pattern>
  <url-pattern>*.inf</url-pattern>
</servlet-mapping> 

2. 注解格式 @WebServlet

@WebServlet(name="xxx", urlPatterns={xxx,xxx,xxx...}, init)

  • name = "StudentInfoServlet" 是用来指定Servlet的名称的, 在整个Web应用程序中必须是唯一的, 这个名称可以在应用程序的其他部分中用来引用或调用Servlet.
  • urlPatterns = {...} 用于指定Servlet将响应的URL模式.
  • initParams = {@WebInitParam(name = "xxx", value = "xxx")},....} 表示传入的初始化参数.
@WebServlet(
		name = "StudentInfoServlet",
		urlPatterns = { "/student/getinfo", "/stu/*", "*.inf" },
		initParams = {
				@WebInitParam(name = "name", value = "peter"),
				@WebInitParam(name = "age", value = "20"),
				@WebInitParam(name = "room", value = "511")
		})
posted @ 2024-03-18 19:59  DawnTraveler  阅读(25)  评论(0编辑  收藏  举报