web專案繼承ServletContainerInitializer進行訪問HttpServlet(WebServlet)
阿新 • • 發佈:2018-12-21
java使用web專案不需要加web.xml
配置javax.servlet.ServletContainerInitializer
1、在src目錄建立META-INF,META-INF目錄下建立services,在services目錄下建立javax.servlet.ServletContainerInitializer檔案
2、配置引用介面ServletContainerInitializer
建立類MyWebConfig
package myWeb; import javax.servlet.ServletContainerInitializer;View Codeimport javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.HandlesTypes; import java.util.Set; @HandlesTypes(value = SpringWeb.class) public class MyWebConfig implements ServletContainerInitializer { @Override public void onStartup(Set<Class<?>> set, ServletContext servletContext) throwsServletException { System.out.println("sadsa"); for (Class<?> aClass : set) { SpringWeb o = null; try { o = (SpringWeb) aClass.newInstance(); o.config(); } catch (InstantiationException e) { e.printStackTrace(); }catch (IllegalAccessException e) { e.printStackTrace(); } } } }
3、介面
package myWeb; public interface SpringWeb { void config(); }
4、實現類
package myWeb; public class SpringWebInitializer implements SpringWeb { //配置 @Override public void config() { System.out.println("初始化"); } }
5、訪問地址HttpServlet
@WebServlet("/asd") public class ServletWeb extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Asdds"); } }
6、tomcat測試: