首页 > 其他分享 >SpringBoot中的Jetty使用及分析

SpringBoot中的Jetty使用及分析

时间:2024-04-13 13:13:28浏览次数:12  
标签:分析 SpringBoot Jetty jetty server context org import new

前言

和 Tomcat 类似,Jetty 也是一个 Web 应用服务器,相对于 Tomcat,Jetty 更加轻量、更加简易、更加灵活。今天通过代码来简单分析下 SpringBoot 中是如何启动 Jetty 的。

Jetty简介

使用

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.AbstractConnector;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.JarResource;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.eclipse.jetty.webapp.AbstractConfiguration;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.util.ClassUtils;

public class TestJetty {

  public static void main(String[] args) throws Exception {
    WebAppContext context = new WebAppContext();
    InetSocketAddress address = new InetSocketAddress((InetAddress) null, getPort());
    configureWebAppContext(context);
    Server server = createServer(address);
    server.setHandler(context);
    server.start();
  }

  private static void configureWebAppContext(WebAppContext context) {
    context.setTempDirectory(getTempDirectory());
    context.setClassLoader(ClassUtils.getDefaultClassLoader());
    context.setContextPath(getContextPath());
    configureDocumentRoot(context);
    addDefaultServlet(context);
    Configuration configuration = new AbstractConfiguration() {
      @Override
      public void configure(WebAppContext context) throws Exception {
        ServletContext ctx = context.getServletContext();
        Dynamic registration = ctx.addServlet("myServlet", new MyServlet());
        registration.setLoadOnStartup(1);
        registration.addMapping("/myServlet");
      }
    };
    Configuration[] configurations = new Configuration[]{configuration};
    context.setConfigurations(configurations);
    context.setThrowUnavailableOnStartupException(true);
  }

  private static void configureDocumentRoot(WebAppContext handler) {
    File docBase = createTempDir("jetty-docbase");
    try {
      List<Resource> resources = new ArrayList<>();
      Resource rootResource = (docBase.isDirectory() ? Resource
          .newResource(docBase.getCanonicalFile())
          : JarResource.newJarResource(Resource.newResource(docBase)));
      resources.add(rootResource);
      handler.setBaseResource(new ResourceCollection(resources.toArray(new Resource[0])));
    } catch (Exception ex) {
      throw new IllegalStateException(ex);
    }
  }

  private static Server createServer(InetSocketAddress address) {
    Server server = new Server();
    server.setConnectors(new Connector[]{createConnector(address, server)});
    return server;
  }

  private static AbstractConnector createConnector(InetSocketAddress address, Server server) {
    ServerConnector connector = new ServerConnector(server, -1, -1);
    connector.setHost(address.getHostString());
    connector.setPort(address.getPort());
    for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) {
      if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) {
        ((HttpConfiguration.ConnectionFactory) connectionFactory).getHttpConfiguration()
            .setSendServerVersion(false);
      }
    }
    return connector;
  }

  private static class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      resp.getWriter().println("hello Jetty");
      resp.getWriter().flush();
    }
  }

  private static void addDefaultServlet(WebAppContext context) {
    ServletHolder holder = new ServletHolder();
    holder.setName("default");
    holder.setClassName("org.eclipse.jetty.servlet.DefaultServlet");
    holder.setInitParameter("dirAllowed", "false");
    holder.setInitOrder(1);
    context.getServletHandler().addServletWithMapping(holder, "/");
    context.getServletHandler().getServletMapping("/").setDefault(true);
  }

  private static File createTempDir(String prefix) {
    try {
      File tempDir = File.createTempFile(prefix + ".", "." + getPort());
      tempDir.delete();
      tempDir.mkdir();
      tempDir.deleteOnExit();
      return tempDir;
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return null;
  }


  private static File getTempDirectory() {
    String temp = System.getProperty("java.io.tmpdir");
    return (temp != null) ? new File(temp) : null;
  }

  private static String getContextPath() {
    return "/testjetty";
  }

  private static int getPort() {
    return 8989;
  }
}

定义一个 WebAppContext,启动 8989 监听端口,代码启动之后,我们可以通过以下地址来访问。
http://localhost:8989/testjetty/myServlet

分析

上述代码完全是参考 SpringBoot 内创建并启动 Jetty 的过程,具体流程如下

  1. SpringBoot 默认使用的 ApplicationContext 实现类为 AnnotationConfigServletWebServerApplicationContext,具体判断逻辑为 ApplicationContextFactory 的 DEFAULT。
  2. AnnotationConfigServletWebServerApplicationContext 继承 ServletWebServerApplicationContext 的 onRefresh() 方法,通过 JettyServletWebServerFactory 的 getWebServer() 方法来创建 WebServer,在这个过程中就会创建 Server 对象并启动。

标签:分析,SpringBoot,Jetty,jetty,server,context,org,import,new
From: https://www.cnblogs.com/strongmore/p/18122793

相关文章

  • SpringBoot使用 nacos 会默认加载项目名配置文件
    问题描述boostrap.yml配置如下spring:application:name:cnblogscloud:nacos:config:server-addr:http://ip:8848namespace:d8b0df04-aa58-4a5b-b582-7d133b9e8b2c#命名空间IDfile-extension:yamlusern......
  • WinDbg分析32位应用程序dump
    使用Windbg对转储文件进行分析的时候,需要注意:1.使用64位的Windbg对64位的进程DUMP进行分析。2.使用32位的Windbg对32位的进程DUMP进行分析。特别对于32位的进程,抓DUMP的时候,需要使用32位的任务管理器进行转储文件创建。32位任务管理器路径:C:\Windows\SysWOW64\Taskmgr.exe,这个......
  • [转帖]内存分析之GCViewer详细解读
    文章目录GCViewer详细解读一,Chart详解二,Eventdetail三,Summary四,Pause五,相关概念5.1GC5.1.1FullGC5.1.2MinorGC5.2垃圾收集器5.2.1串行收集器(Serial)5.2.2**ParNew收集器**5.2.3**ParallelScavenge**收集器**5.2.4CMS收集器(ConcurrentMarkSweep)****5.2.5G1......
  • 在线直播系统源码,前后端大文件上传代码分析
    在线直播系统源码,前后端大文件上传代码分析前端代码:<template><div><[email protected]="hanldeClick"class="upload_container"><inputname="请上传文件"type="file"ref="uploadRef"......
  • springboot集成redis
    首先引入依赖<!--redis坐标--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>在yml中引入redis数据库spring......
  • 【专题】2023年新能源汽车及用户调研分析报告PDF合集分享(附原数据表)
    原文链接:https://tecdat.cn/?p=34315原文出处:拓端数据部落公众号2022年,尽管受疫情频发、芯片结构性短缺、动力电池原材料价格高位运行等多方面影响,中国汽车市场却在逆境中整体复苏向好,总体实现正增长,全年销量完成2686万辆;在国内强大的消费市场促进下,乘用车市场已连续8年超过2千......
  • Thymeleaf SSTI模板注入分析
    环境搭建先搭建一个SpringMVC项目,参考这篇文章,或者参考我以前的spring内存马分析那篇文章https://blog.csdn.net/weixin_65287123/article/details/136648903SpringMVC路由简单写个servletpackagecom.example.controller;importorg.springframework.stereotype.Controlle......
  • TSINGSEE青犀AI智能分析网关V4叉车载货出入库检测算法介绍及应用
    随着物流行业的快速发展,叉车作为物流运输的重要设备,其安全性和效率性越来越受到人们的关注。然而,在实际操作中,由于人为因素和操作环境的复杂性,叉车事故时有发生,给企业和个人带来了巨大的损失。为了提高叉车运输的安全性和效率,近年来,人工智能技术逐渐应用于叉车运输领域,其中,叉车载......
  • TSINGSEE青犀AI智能分析网关V4人员睡岗检测算法介绍及应用
    人员睡岗AI算法是一种通过人工智能技术来检测和预警人员是否处于睡眠状态的算法。它主要通过分析人员的行为、姿势和身体特征等信息来判断人员是否已经进入睡眠状态。该算法通过对监控摄像头捕捉的画面进行实时分析,利用卷积神经网络(CNN)对图像进行特征提取,进而判断画面中的人员是否......
  • Springboot2+vue2整合项目
    前端https://blog.csdn.net/m0_37613503/article/details/128961447数据库1.用户表CREATETABLE`x_user`(`id`int(11)NOTNULLAUTO_INCREMENT,`username`varchar(50)NOTNULL,`password`varchar(100)DEFAULTNULL,`email`varchar(50)DEFAULTNULL,`......