加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在java应用程序中嵌入jetty并导出为jar

发布时间:2020-12-15 02:30:12 所属栏目:Java 来源:网络整理
导读:我正在制作一个嵌入Jetty Web服务器的 Java应用程序,该服务器反过来提供使用Google Web Toolkit开发的内容.它在 Eclipse中运行时一切正常,但是当我将它作为jar文件导出时,我得到的是一条Jetty错误消息“File not found”. Jetty服务器的启动方式如下: WebAp
我正在制作一个嵌入Jetty Web服务器的 Java应用程序,该服务器反过来提供使用Google Web Toolkit开发的内容.它在 Eclipse中运行时一切正常,但是当我将它作为jar文件导出时,我得到的是一条Jetty错误消息“File not found”.

Jetty服务器的启动方式如下:

WebAppContext handler = new WebAppContext();
    handler.setResourceBase("./war");
    handler.setDescriptor("./war/WEB-INF/web.xml");
    handler.setContextPath("/");
    handler.setParentLoaderPriority(true);
    server.setHandler(handler);

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

我怀疑问题是handler.setResourceBase()和handler.setDescriptor()中使用的相对路径.我用谷歌搜索并测试了很多解决方案,但到目前为止无济于事.特别是我尝试过使用像getClass().getResource(“./ war”).toExternalForm()这样的东西,但这只会抛出Null异常.

我也尝试过:

ProtectionDomain protectionDomain = Start.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();

但这只会导致Jetty服务于java类的目录列表.

有没有办法做到这一点?

解决方法

>将已编译的GWT应用程序的所有文件复制到一个Java包中.例如:

my.webapp.resources
  html/MyPage.html
  gwtmodule/gwtmodule.nocache.js
  ...

(html,gwtmodule也将成为Java包).
>配置嵌入式Jetty实例以提供这些文件.

final String webDir = this.getClass().
       getClassLoader().getResource("my/webapp/resources").toExternalForm();

 final Context root = new Context(server,"/",Context.SESSIONS);
 root.setContextPath("/");
 root.setResourceBase(webDir);
 root.addServlet(MyGwtService.class,"/servlets/v01/gwtservice");

当应用程序从eclipse运行以及部署时,这种方法对我都有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读