玩转springboot之springboot注册servlet

springboot注册servlet

有时候在springboot中依然需要注册servlet,filter,listener,就以servlet为例来进行说明,另外两个也都类似

使用@WebServlet注解

在servlet3.0之后,servlet注册支持注解注册,而不需要在web.xml中进行配置,类似的,对于Filter使用@WebFilter注解,对于Listener使用@WebListener注解

复制代码
@WebServlet(name = "helloWorldServlet",urlPatterns = "/helloWorldServlet",
initParams = {
        @WebInitParam(name = "name",value = "张三")
})
public class HelloWorldServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = getServletConfig().getInitParameter("name");
        System.out.println("helloWorldServlet ---- doPost");
        resp.getOutputStream().println(name);
    }
}

使用ServletRegistrationBean

springboot为注册servlet专门提供了一个bean,可以使用该bean进行注册,类似的对于Filter提供了FilterRegistrationBean,对于Listener提供了ServletListenerRegistrationBean

复制代码
@Configuration
public class ServletRegistConfig {

    @Bean
    public ServletRegistrationBean registServlet(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        // servlet
        servletRegistrationBean.setServlet(new RegistServlet());
        List<String> urlMappings = new ArrayList<>();
        urlMappings.add("/registServlet");
        // 地址映射
        servletRegistrationBean.setUrlMappings(urlMappings);
        // servlet名称
        servletRegistrationBean.setName("registServlet");

        Map<String,String> initMap = new HashMap<>();
        initMap.put("name","李四");
        // servlet的初始参数
        servletRegistrationBean.setInitParameters(initMap);

        return servletRegistrationBean;

    }
}

动态注册

springboot中还提供了动态注册的方式,需要实现ServletContextInitializer接口

复制代码
@Component
public class ServletRegistConfiguration implements ServletContextInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("registServlet", RegistServlet.class);
        // 地址映射
        dynamic.addMapping("/regist");
        // servlet的初始参数
        dynamic.setInitParameter("name","王五");
    }
}

https://zhhll.icu/2021/框架/springboot/基础/11.springboot注册servlet/

本文由mdnice多平台发布

相关推荐
张较瘦_5 分钟前
SpringBoot3 | SpringBoot中Entity、DTO、VO的通俗理解与实战
java·spring boot·后端
may_一一25 分钟前
docker安装的redis状态一直是restarting
java·redis·docker
zhangyifang_00927 分钟前
Spring中的SPI机制
java·spring
han_hanker1 小时前
这里使用 extends HashMap<String, Object> 和 类本身定义变量的优缺点
java·开发语言
careathers1 小时前
【JavaSE语法】面向对象初步认识
java·面向对象
coding随想1 小时前
掌控选区的终极武器:getSelection API的深度解析与实战应用
java·前端·javascript
嵌入式小能手1 小时前
飞凌嵌入式ElfBoard-文件I/O的深入学习之存储映射I/O
java·前端·学习
ChinaRainbowSea2 小时前
github 仓库主页美化定制
java·后端·github
程序猿小蒜2 小时前
基于springboot的医院资源管理系统开发与设计
java·前端·spring boot·后端·spring
程序员-周李斌2 小时前
ConcurrentHashMap 源码分析
java·开发语言·哈希算法·散列表·开源软件