springMvc整合undertow容器

    因为项目要求用springMvc,但是默认以war包发布到tomact下每一次
    启动都会很慢,所以希望能用一个嵌入式的web容器,了解到
    undertow对于小型项目还不错,就使用了undertow.
    
    最开始用的Jfinal-undertow,但是突然看到出了spring6.0,就想体验
    一下,spring6.0对应的servlet版本比较高,jfinal-undertow并不兼容,
    所以就自己找到了undertow进行使用,以下就是折腾的经历。

1. 依赖安装


<!-- https://mvnrepository.com/artifact/io.undertow/undertow-servlet -->
<dependency>
  <groupId>io.undertow</groupId>
  <artifactId>undertow-servlet</artifactId>
  <version>2.3.3.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.undertow/undertow-core -->
<dependency>
  <groupId>io.undertow</groupId>
  <artifactId>undertow-core</artifactId>
  <version>2.3.3.Final</version>
</dependency>

在项目原本的依赖下加入以上两个依赖,版本需要对应一样,分别是undertow的核心依赖和undertow的servlet相关实现。

2. 运行整合

2.1 添加servlet

// 创建servletInfo,指定servlet的命名和servlet对应的class
ServletInfo info = new ServletInfo("mvc", DispatcherServlet.class)
        // 添加映射路径
        .addMapping("/")
        // 设置InitParam,制定了spring-mvc的配置文件位置
        .addInitParam("contextConfigLocation","classpath:spring-config/spring-mvc.xml")
        // 设置什么时候进行初始化
        .setLoadOnStartup(1);

2.2 创建容器

undertow的一个web容器就是一个DeploymentManager,该接口的默认实现类就是DeploymentManagerImpl,然后需要两个参数,分别是DeploymentInfoServletContainer,所以需要先创建DeploymentInfo,然后创建ServletContainer,因为ServletContainer也需要DeploymentInfo作为参数,代码如下所示。

// 创建DeploymentInfo 对象
DeploymentInfo deploymentInfo = new DeploymentInfo()
                // 指定类加载器
                .setClassLoader(TestServer.class.getClassLoader())
                // 设置contextPath
                .setContextPath("/")
                // 设置容器名称
                .setDeploymentName("myUndertow")
                // 设置初始化参数,制定了spring的配置文件的位置
                .addInitParameter("contextConfigLocation","classpath:spring-config/spring.xml")
                // 设置了一个监听器,用于初始化spring
                .addListener(new ListenerInfo(ContextLoaderListener.class))
                // 添加servlet
                .addServlet(info)
                // 添加一个过滤器,放置乱码问题
                .addFilter(
                        new FilterInfo("Encoding", CharacterEncodingFilter.class)
                        .addInitParam("encoding","utf-8")
                );
        // 创建一个ServletContainer,并添加deploymentInfo
        ServletContainerImpl container = new ServletContainerImpl();
        container.addDeployment(deploymentInfo)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值