You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Main类使用Jetty部署Vaadin应用的WAR文件

嘿,我帮你把这段代码补全并整理成可直接运行的版本,这样你就能通过Main类启动Jetty服务器,加载你的Vaadin WAR应用了:

用Main类启动Jetty并部署Vaadin WAR应用

你的代码已经搭好了Jetty服务器和连接器的基础框架,但WebAppContext的配置部分不完整,我帮你补全并完善整个流程:

完整可运行代码

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;
import java.io.File;

public class Main {
    public static void main(String[] args) throws Exception {
        // 初始化Jetty服务器实例
        final Server server = new Server();
        
        // 配置HTTP连接器,监听3131端口
        final ServerConnector connector = new ServerConnector(server);
        connector.setPort(3131);
        server.setConnectors(new ServerConnector[]{connector});
        
        // 配置Web应用上下文,用于加载Vaadin WAR包
        final WebAppContext webappContext = new WebAppContext();
        final File warFile = new File("target/avx-gcms-1.0.war");
        
        // 设置类加载器,确保能正确加载Vaadin相关类资源
        webappContext.setClassLoader(Thread.currentThread().getContextClassLoader());
        // 指定WAR包的绝对路径,让Jetty识别并加载
        webappContext.setWar(warFile.getAbsolutePath());
        // 设置应用的上下文路径(访问时用 http://localhost:3131/avx-gcms 即可打开应用)
        webappContext.setContextPath("/avx-gcms");
        
        // 将Web应用上下文添加到服务器的处理器集合
        ContextHandlerCollection contexts = new ContextHandlerCollection();
        contexts.addHandler(webappContext);
        server.setHandler(contexts);
        
        // 启动服务器并等待关闭信号
        server.start();
        System.out.println("Jetty服务器已启动,访问地址:http://localhost:3131/avx-gcms");
        server.join();
    }
}

关键注意事项

  • WAR包路径验证:运行前确保target/avx-gcms-1.0.war已生成,可先执行mvn package(Maven项目)或对应构建命令打包
  • 依赖配置:项目需要引入Jetty核心依赖,以Maven为例,pom.xml中需添加:
    <dependencies>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>11.0.15</version> <!-- 选择与你的Vaadin版本兼容的Jetty版本,比如Vaadin24.x推荐Jetty11+ -->
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-webapp</artifactId>
            <version>11.0.15</version>
        </dependency>
        <!-- Vaadin相关依赖需确保已正确打包进WAR包 -->
    </dependencies>
    
  • 上下文路径调整:如果不需要特定路径,可将setContextPath("/avx-gcms")改为setContextPath("/"),此时访问地址为http://localhost:3131/

直接运行这个Main类就能启动Jetty并加载你的Vaadin应用了。

内容的提问来源于stack exchange,提问作者Bleach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:56:54