需要注意的是,如果使用Servlet 3.0版本的话:首先Tomcat服务器必须使用7.0版本以上的(老版本不提供3.0版本),其次Eclipse创建Web工程时选择3.0版本。
Servlet 3.0版本允许使用注解方式来替代web.xml文件中配置Servlet、Filter和Listener的信息,首先回忆一下web.xml文件是如何配置Servlet、Filter和Listener的:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 配置Servlet -->
<servlet>
<servlet-name>ServletTest</servlet-name>
<servlet-class>app.java.servlet.ServletTest</servlet-class>
<init-param>
<param-name>longestory</param-name>
<param-value>龙哥有话说</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- 配置Filter -->
<filter>
<filter-name>FilterTest</filter-name>
<filter-class>app.java.servlet.FilterTest</filter-class>
<init-param>
<param-name>longestory</param-name>
<param-value>龙哥有话说</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>FilterTest</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置Listener -->
<listener>
<listener-class>app.java.servlet.ListenerTest</listener-class>
</listener>
</web-app>
使用注解替代web.xml文件配置Servlet。
@WebServlet(urlPatterns="/*",initParams={@WebInitParam(name="longestory",value="龙哥有话说")},loadOnStartup=0)
public class ServletTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
}
}
使用注解替代web.xml文件配置Filter。
@WebFilter(urlPatterns="/*",initParams={@WebInitParam(name="longestory",value="龙哥有话说")})
public class FilterTest implements Filter {
@Override
public void init(FilterConfig arg0) throws ServletException {}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
}
@Override
public void destroy() {}
}
使用注解替代web.xml文件配置Listener。
@WebListener
public class ListenerTest implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent arg0) {}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {}
}
转载说明:请注明作者及原文链接,谢谢!