因为项目要求用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,然后需要两个参数,分别是DeploymentInfo和ServletContainer,所以需要先创建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)