当前位置: 代码迷 >> 综合 >> Servlet3.0中的web组件注册
  详细解决方案

Servlet3.0中的web组件注册

热度:90   发布时间:2024-02-25 18:02:48.0

Servlet3.0中的注册

1.依赖

TomCat官网标准:
在这里插入图片描述
导入maven依赖:

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version>   <!--这里的版本不能低于3.0--><scope>provided</scope>
</dependency>

2.Servlet注册

定义一个servlet,通过注解将其注入到Servlet容器中

  • 使用@WebServlet注解标识该类
    • name属性对应xml中servlet标签的servlet-name属性
    • urlPatterns属性对应servletMapping标签中的url-pattern属性,可以指定一个也可以指定多个
    • loadOnStartUp属性对应servlet标签的loadOnStartUp属性
    • initParams属性对应servlet标签中的init-param属性
@WebServlet(name = "abc",urlPatterns ="/abc" ,loadOnStartup = 2,initParams = {@WebInitParam(name = "cs1",value = "z1"),@WebInitParam(name = "cs2",value = "z2")
})
public class DemoServlet extends HttpServlet {//用来获取init参数@Overridepublic void init() throws ServletException {System.out.println(this.getInitParameter("cs1"));System.out.println(this.getInitParameter("cs2"));}//构造方法,用来检验loadOnStartUppublic DemoServlet() {System.out.println("demo被实例化");}//配合urlPatterns表示请求地址@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().write("demo servlet");}
}

显示结果:
在这里插入图片描述
在这里插入图片描述

3.Listener注册

  • 使用@WebListener注解标识该类
  • 该类实现对应的监听器接口
@WebListener
public class DemoListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {System.out.println("ServletContext被创建");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {System.out.println("ServletContext被销毁");}
}

在这里插入图片描述
在这里插入图片描述

4.Filter注册

  • 使用@WebFilter注解标识该类
    • filterName属性对应xml中filter标签的name属性
    • urlPatterns属性对应filter标签的url-pattern属性
    • initParams属性对应init-param标签
  • 实现Filter接口
@WebFilter(filterName = "aaa",urlPatterns = "/abc",initParams ={@WebInitParam(name = "f1",value="ff1"),@WebInitParam(name = "f2",value="ff2"),} )
public class DemoFilter implements Filter {//初始化获取Init参数@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println(filterConfig.getInitParameter("f1"));System.out.println(filterConfig.getInitParameter("f2"));}//拦截后放行@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {chain.doFilter(request,response);}//销毁@Overridepublic void destroy() {System.out.println("Filter destory");}
}

在这里插入图片描述
在这里插入图片描述

5.动态注册web组件

web组件的优先级:Listener—>Filter—>Servlet
动态注册web组件主要适用于第三方开发的web组件,我们没办法直接加web注解
通过ServletContext对象来注册
在这里插入图片描述

  • 创建时机:
    • 在ServletContextListener中进行创建,限制性是没办法新增ServletContextListener

模拟第三方监听器

public class Demo3Listener implements HttpSessionListener {@Overridepublic void sessionCreated(HttpSessionEvent se) {System.out.println("Demo3SessionListener创建");}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {System.out.println("Demo3SessionListener销毁");}
}

ServletContextListener监听器进行加载


@WebListener
public class Demo2Listener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {ServletContext servletContext = sce.getServletContext();servletContext.addListener(Demo3Listener.class);}@Overridepublic void contextDestroyed(ServletContextEvent sce) {}
}

在servlet中获取session(目的是防止session对象没有被创建)

    @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession();resp.getWriter().write("demo servlet");}

显示结果:
在这里插入图片描述

模拟第三方过滤器


public class Demo2Filter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("Demo2Filter被创建");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {chain.doFilter(request,response);}@Overridepublic void destroy() {System.out.println("Demo2Filter被销毁");}
}
@WebListener
public class Demo2Listener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {ServletContext servletContext = sce.getServletContext();//新增FilterFilterRegistration.Dynamic demo2 = servletContext.addFilter("Demo2", Demo2Filter.class);//放置参数Map initParam = new HashMap();initParam.put("2f","fff2");//传递init参数demo2.setInitParameters(initParam);//dispatcherTypes设置为null时默认为DispatcherType.REQUESTdemo2.addMappingForUrlPatterns(null,false,"/abc");}

显示结果:
在这里插入图片描述

在这里插入图片描述
模拟第三方servlet

public class Demo2Servlet extends HttpServlet {@Overridepublic void init() throws ServletException {System.out.println("Demo2Servlet被创建");}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}@Overridepublic void destroy() {System.out.println("Demo2Servlet被销毁");}
}
@WebListener
public class Demo2Listener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {ServletContext servletContext = sce.getServletContext();//放置参数Map initParam = new HashMap();initParam.put("2f","fff2");//新赠servletServletRegistration.Dynamic demo21 = servletContext.addServlet("demo2", Demo2Servlet.class);//设置启动时机demo21.setLoadOnStartup(2);//设置init参数demo21.setInitParameters(initParam);//设置请求路径demo21.addMapping("/abc");}

在这里插入图片描述
在这里插入图片描述
* ServletContainerInitializer 新增API
创建自己的 DemoServletContainerInitializer实现ServletContainerInitializer接口

public class DemoServletContainerInitializer implements ServletContainerInitializer {@Overridepublic void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {//创建Listenerctx.addListener(DemoListener.class);//新增FilterFilterRegistration.Dynamic demo2 = ctx.addFilter("Demo2", Demo2Filter.class);//放置参数Map initParam = new HashMap();initParam.put("2f","fff2");demo2.setInitParameters(initParam);//传递init参数//dispatcherTypes设置为null时默认为DispatcherType.REQUESTdemo2.addMappingForUrlPatterns(null,false,"/abc");//新赠servletServletRegistration.Dynamic demo21 = ctx.addServlet("demo2", Demo2Servlet.class);//设置启动时机demo21.setLoadOnStartup(2);//设置init参数demo21.setInitParameters(initParam);//设置请求路径demo21.addMapping("/abc");}
}

DemoListener

public class DemoListener implements ServletContextListener   {@Overridepublic void contextInitialized(ServletContextEvent sce) {System.out.println("ServletContext被创建");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {System.out.println("ServletContext被销毁");}}

Filter

public class Demo2Filter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("Demo2Filter被创建");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {chain.doFilter(request,response);}@Overridepublic void destroy() {System.out.println("Demo2Filter被销毁");}
}

servlet

public class Demo2Servlet extends HttpServlet {@Overridepublic void init() throws ServletException {System.out.println("Demo2Servlet被创建");}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}@Overridepublic void destroy() {System.out.println("Demo2Servlet被销毁");}
}

在这里插入图片描述

在文件中写入自己创建的实现类的全包名
在这里插入图片描述
显示结果:
在这里插入图片描述
在这里插入图片描述