Spring Boot如何配置嵌入式Jetty使用ServletContextHandler替代WebAppContext
配置Spring使用ServletContextHandler替代WebAppContext
1. Spring Boot 场景配置
如果是Spring Boot集成Jetty,通过自定义Jetty服务器配置替换默认的WebAppContext:
- 创建配置类,自定义Jetty服务器的Handler:
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JettyCustomConfig { @Bean public WebServerFactoryCustomizer<JettyServletWebServerFactory> jettyServerCustomizer() { return factory -> factory.addServerCustomizers(server -> { // 移除默认WebAppContext server.getHandlers()[0].stop(); server.removeHandler(server.getHandlers()[0]); // 初始化ServletContextHandler // 若需满足Jetty会话强制要求,使用SESSIONS(默认);无需会话则用NO_SESSIONS ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS); handler.setContextPath("/"); // 注册Spring DispatcherServlet handler.addServlet(org.springframework.web.servlet.DispatcherServlet.class, "/"); // 设置Spring配置文件路径,按需调整 handler.setInitParameter("contextConfigLocation", "classpath:spring-mvc.xml"); server.setHandler(handler); }); } }
2. 传统Spring MVC(非Boot)场景配置
手动启动Jetty并配置ServletContextHandler:
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class JettyBootstrap { public static void main(String[] args) throws Exception { Server server = new Server(8080); // 初始化ServletContextHandler,SESSIONS模式满足Jetty会话要求 ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); contextHandler.setContextPath("/"); // 配置Spring根上下文 XmlWebApplicationContext rootContext = new XmlWebApplicationContext(); rootContext.setConfigLocation("classpath:applicationContext.xml"); contextHandler.addEventListener(new ContextLoaderListener(rootContext)); // 配置Spring MVC调度Servlet XmlWebApplicationContext mvcContext = new XmlWebApplicationContext(); mvcContext.setConfigLocation("classpath:spring-mvc.xml"); contextHandler.addServlet(new DispatcherServlet(mvcContext), "/"); server.setHandler(contextHandler); server.start(); server.join(); } }
核心说明
- ServletContextHandler是Jetty的轻量上下文实现,仅提供Servlet基础支持,不会加载WebAppContext自带的WAR部署、JSP引擎等冗余特性,适配你的无会话业务场景。
- 针对Jetty会话强制要求:只需使用
ServletContextHandler.SESSIONS模式(默认配置)即可满足要求,业务代码可选择不使用会话功能,无需额外配置复杂的会话管理器。
内容的提问来源于stack exchange,提问作者Anonymous Person
相关产品推荐
相关产品推荐

