servlet 基于注解开发:
index.jsp中
<a href="hello">hello</a>
新建HelloServlet类
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
resp.getWriter().write("hello...");
}
}
Shared libraries 共享库 / runtimes pluggability(运行时插件能力)
1.Servlet容器启动会扫描,当前应用里面每一个jar包的ServletContainerInitializer的实现
2.提供ServletContainerInitializer的实现类:
必须绑定在:META-INF/services/javax.servlet.ServletContainerInitialize文件的内容就说ServletContainerInitilizer实现类的全类名
总结:容器在启动应用的时候,会扫描当前应用每一个jar包里面。META-INF/services/javax.servlet.ServletContainerInitializer指定的实现类,启动并运行这个实现类的方法
使用ServletContext注册Web组件(Servlet,Filter,Listener)
使用编码的方式,在项目启动的时候给ServletContext里面添加组件,必须在项目启动的时候添加:
1)ServletContainerInitializer得到的ServletContext
2)ServletContextListener得到的ServletContext
//容器启动的时候会将@HandlesTypes指定的这个类型下面的子类(实现类,子接口等)传递过来
@HandlesTypes(value = {HelloService.class}) //传入感兴趣的类型
public class MyServletContainerInitializer implements ServletContainerInitializer {
//应用启动的时候,会运行onStartup方法
//ServletContext arg1:代表当前web应用的ServletContext
//Set<Class<?>> arg0:感兴趣的类型的所有子类型
@Override
public void onStartup(Set<Class<?>> arg0, ServletContext sc) throws ServletException {
System.out.println("感兴趣的类型");
for (Class<?> claz : arg0){
System.out.println(claz);
}
//注册组件 ServletRegistration
ServletRegistration.Dynamic servlet = sc.addServlet("userServlet", new UserServlet());
//配置servlet的配置信息
servlet.addMapping("/user");
//注册监听器
sc.addListener(UserListener.class);
//注册Filter FilterRegistration
FilterRegistration.Dynamic filter = sc.addFilter("userFillter", UserFilter.class);
//配置filter的映射信息
filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
}
}
Servlet类:
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
resp.getWriter().write("tomcat");
}
}
Filter类:
public class UserFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
//过滤请求
System.out.println("UserFilter..doFilter..");
//运行
arg2.doFilter(arg0,arg1);
}
@Override
public void destroy() {
}
}
Listener类:
//监听项目的启动和停止
public class UserListener implements ServletContextListener {
//监听ServletContext启动初始化
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("UserListener...contextInitialized");
}
//监听ServletContext销毁
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("UserListener...contextDestroyed");
}
}