一、依赖
<!--Jetty服务器的核心依赖项,用于创建和管理服务器。--><dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-server</artifactId><version>9.4.43.v20210629</version></dependency><!-- Jetty的Servlet支持依赖项,用于处理Servlet相关的功能。--><dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-servlet</artifactId><version>9.4.43.v20210629</version></dependency><!-- Jersey的Servlet容器依赖项,用于支持JAX-RS(Java API for RESTful Web Services)的实现--><dependency><groupId>org.glassfish.jersey.containers</groupId><artifactId>jersey-container-servlet</artifactId><version>2.34</version></dependency><!-- Jersey的HK2依赖项,用于依赖注入和管理。--><dependency><groupId>org.glassfish.jersey.inject</groupId><artifactId>jersey-hk2</artifactId><version>2.34</version></dependency><!-- JAX-RS API的依赖项,提供了构建RESTful接口的核心功能。--><dependency><groupId>javax.ws.rs</groupId><artifactId>javax.ws.rs-api</artifactId><version>2.1.1</version></dependency>
二、启动类
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.example.controller.HelloWorldResource;public class App {public static void main(String[] args) throws Exception {Server server = new Server(8088); // 创建Jetty服务器并指定端口号为8088ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);context.setContextPath("/"); // 设置Servlet上下文路径为根路径 "/"server.setHandler(context); // 将Servlet上下文设置为服务器的处理程序ServletHolder holder = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");// 将Jersey的ServletContainer添加到Servlet上下文中,映射到所有请求路径 "/*"holder.setInitOrder(0);holder.setInitParameter("jersey.config.server.provider.classnames", HelloWorldResource.class.getCanonicalName());// 配置Jersey的ServletContainer,指定要提供的RESTful资源类为HelloWorldResourceserver.start(); // 启动Jetty服务器server.join(); // 阻塞主线程,直到服务器停止}}
三、接口
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;@Path("/hello")
public class HelloWorldResource {@GET@Produces(MediaType.TEXT_PLAIN)public String sayHello() {return "Hello, World!";}
}
四、测试
http://localhost:8088/hello