Servlet 3.0 規範(一)註解規範
阿新 • • 發佈:2019-01-01
Servlet 3.0 規範(一)註解規範
一、基本使用
在 Servlet 3.0 時支援註解啟動,不再需要 web.xml 配製檔案。
1.1 Servlet 3.0 註解
Servlet 3.0 常用註解: @WebServlet @WebFilter @WebInitParam @WebListener
@WebServlet("/hello") public class HelloServert extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("hello"); } }
Tomcat 7.x 以上的版本啟動,訪問
Tomcat 6.x 實現 Servert 2.5
Tomcat 7.x 實現 Servert 3.0
Tomcat 8.x 實現 Servert 3.1
Tomcat 9.x 實現 Servert 4.0
1.2 ServletContainerInitializer
Servlet 容器啟動會掃描當前應用的每一個 jar 包 ServletContainerInitializer 的實現。
通過每個 jar 包下的 META-INFO/services/javax.servlet.ServletContainerInitializer 檔案:
com.github.binarylei.MyServletContainerInitializer
@HandlesTypes(HelloServert.class) public class MyServletContainerInitializer implements ServletContainerInitializer { /** * @param c @HandlesTypes 指定,HelloServert 子類 * @param ServletContext 註冊三大元件(Servlet Filter Listener) */ @Override public void onStartup(Set<Class<?>> set, ServletContext ctx) throws ServletException { // 1. 處理感興趣的類 System.out.println(set); // 2.1. 註冊 Servert ServletRegistration.Dynamic servlet = ctx.addServlet("myServlet", HelloServert.class); servlet.addMapping("/*"); // 2.2. 註冊 Listener ctx.addListener(MyServletContextListener.class); // 2.3. 註冊 Filter FilterRegistration.Dynamic filter = ctx.addFilter("myFileter", MyFilter.class); filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); } }
在 Servlet 3.0 時支援註解啟動,其中 ServletContainerInitializer 和 HandlesTypes 都是 Servlet 3.0 的規範。
ServletContainerInitializer
只有一個方法 onStartupHandlesTypes
感興趣的類,啟動時會通過 onStartup 傳遞給 clazzs 引數。HandlesTypes 會找到 HelloServert 所有的子類(不包括 HelloServert 自己)
每天用心記錄一點點。內容也許不重要,但習慣很重要!