Servlet3.0

编程

Shared Libraries(共享库) / runtime pluggability(运行时插件能力)

  1. Servlet容器启动会扫描,当前jar包里每一个实现了ServletContainerInitializer的实现
  2. 提供ServletContainerInitializer的实现类,必须绑定在META-INF/services/javax.servlet.ServletContainerInitializer

总结

  1. 容器在启动应用时,会扫描当前应用每一个jar包里面META-INF/services/javax.servlet.ServletContainerInitializer

    指定的实现类启动并运行这个实现类,并且可以传入指定的类型

MyServletContainerInitializer.class

/**

* 容器启动时会将@HandlesTypes指定的这个类型下面的子类(实现类、子接口)传递过来

*/

@HandlesTypes(value = {HelloService.class})

public class MyServletContainerInitializer implements ServletContainerInitializer {

/**

* @param set @HandlesTypes传入的指定的类型的子类型

* @param servletContext 代表当前web应用的servletContext,一个web应用一个servletContext

*

* 1. 使用servletContext注册Servlet,Filter,Listener

* 2. 使用编码的方式,在项目启动时给ServletContext里增加组件,必须在项目启动时添加

* 1. ServletContainerInitializer得到的servletContext

* 2. ServletContextListener得到的servletContext

*/

public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {

for (Class clazz : set) {

System.out.println(clazz);

}

//注册组件ServletRegistration

ServletRegistration.Dynamic userServlet = servletContext.addServlet("userServlet", new UserServlet());

userServlet.addMapping("/user");

//注册监听

servletContext.addListener(UserListener.class);

//注册FilterRegistration组件

FilterRegistration.Dynamic userFilter = servletContext.addFilter("userFilter", UserFilter.class);

userFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/user");

}

}

UserFilter.class

public class UserFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)

throws IOException, ServletException {

filterChain.doFilter(servletRequest, servletResponse);

}

public void destroy() {

}

}

UserListener.class

/**

* 监听项目的启动和停止

*/

public class UserListener implements ServletContextListener {

/**

* 监听servletContextEvent的初始化

*/

public void contextInitialized(ServletContextEvent servletContextEvent) {

System.out.println("UserListener.......contextInitialized.......");

}

/**

* 监听servletContextEvent的销毁

*/

public void contextDestroyed(ServletContextEvent servletContextEvent) {

System.out.println("UserListener.......contextDestroyed.......");

}

}

UserServlet.class

public class UserServlet extends HttpServlet {

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

super.doPost(req, resp);

}

}

以上是 Servlet3.0 的全部内容, 来源链接: utcz.com/z/517100.html

回到顶部