嵌入式Jetty开发之代码启动Jetty

,# 嵌入式Jetty开发之代码启动Jetty
目前正在做嵌入式Jetty开发,把遇到的问题写出来,希望可以帮到有同样问题的小伙伴,也方便自己下次遇到同样问题时查看

背景:之前项目用Tomcat,然后老大说新项目采用Jetty代码启动,让我先进行调研和使用
最开始看Jetty的官方文档,配合某位大牛的中文翻译文档,然后遇到各种问题各种查网上的资料
最后修改主要这两个文件:

  • POM配置文件
  • 主类代码

POM配置文件

之前加了太多相关的配置文件,然后生产模式war包运行各种出错,然后删掉了一些依赖就好了,想必是画蛇添足,造成了类的冲突,这是修改后的文件:

    <properties>
        <spring.version>4.3.6.RELEASE</spring.version>
        <jetty.version>9.3.21.v20170918</jetty.version>
    </properties>

    <dependencies>
        <!-- jetty -->
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope> <!-- 开发模式去掉这个 -->
        </dependency>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-webapp</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope><!-- 开发模式去掉这个 -->
        </dependency>
    </dependencies>
    <build>
        <finalName>文件名称</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.my.example.JettyLauncher</mainClass>
                        </manifest>
                    </archive>
                    <warName>${project.artifactId}-standalone</warName>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <id>main-class-placement</id>
                        <phase>prepare-package</phase>
                        <configuration>
                            <target>
                                <move todir="${project.build.directory}/${project.artifactId}/">
                                    <fileset dir="${project.build.directory}/classes/">
                                        <include name="**/*/JettyLauncher.class" />
                                    </fileset>
                                </move>
                            </target>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <id>jetty-classpath</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>unpack-dependencies</goal>
                        </goals>
                        <configuration>
                            <includeGroupIds>org.eclipse.jetty, org.eclipse.jetty.orbit,
                                javax.servlet</includeGroupIds>
                            <includeScope>provided</includeScope>
                            <!-- remove some files in order to decrease size -->
                            <excludes>*, about_files/*, META-INF/*</excludes>
                            <!-- <excludeArtifactIds>jsp-api,jstl</excludeArtifactIds> -->
                            <outputDirectory>
                                ${project.build.directory}/${project.artifactId}
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!-- to support compilation in linux -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <target>1.6</target>
                    <source>1.6</source>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

JettyLauncher

jetty启动的主类代码:

public class JettyLauncher {
    public static final int PORT = 8080;
    public static final String CONTEXT = "/test";
    private static final String DEFAULT_WEBAPP_PATH = "src/main/webapp";
    /**
     * 创建用于生产环境的Jetty Server
     */
    public static Server createProdServer(int port, String contextPath) {

        Server server = new Server(port);
        server.setStopAtShutdown(true);

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

        String warFile = location.toExternalForm();
        System.out.println("war file path:"+warFile);
        WebAppContext context = new WebAppContext(warFile, contextPath);
        context.setServer(server);

        // 设置work dir,war包将解压到该目录,jsp编译后的文件也将放入其中。
        String currentDir = new File(location.getPath()).getParent();
        File workDir = new File(currentDir, "work");
        context.setTempDirectory(workDir);

        server.setHandler(context);
        return server;
    }

    /**
     * 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录.
     */
    public static Server createDevServer(int port, String contextPath) {
        Server server = new Server();
        // 设置在JVM退出时关闭Jetty的钩子。
        server.setStopAtShutdown(true);

        //这是http的连接器
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(port);
        // 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
        connector.setReuseAddress(false);
        server.setConnectors(new Connector[] { connector });

        WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, contextPath);
        //webContext.setContextPath("/");
        webContext.setDescriptor("src/main/webapp/WEB-INF/web.xml");
        // 设置webapp的位置
        webContext.setResourceBase(DEFAULT_WEBAPP_PATH);
        webContext.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(webContext);
        return server;
    }

    /**
     * 启动jetty服务
     *
     * @param port
     * @param context
     */
    public void startJetty(int port, String context, String env) {
        Server server = null;
        if ("dev".equals(env)) {
            server= JettyLauncher.createDevServer(port, context);
        }else {
            server= JettyLauncher.createProdServer(port, context);
        }
        try {
            server.stop();
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
    public static void main(String[] args) {
        new JettyLauncher().startJetty(8080, "/test,"dev");//dev为开发模式
    }
}

开发模式:去掉依赖中的<scope>provide<scope>以及main函数参数为dev,然后运行主类即可
生产模式:
        打包: mvn package    
              cd target
              java -jar xx.war

主要参考:
[1]:嵌入式Jetty Web开发

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值