jetty服务器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhoujiaping123/article/details/83036443

maven配置依赖

		<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-server -->
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-server</artifactId>
			<version>9.4.12.RC2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-webapp -->
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-webapp</artifactId>
			<version>9.4.12.RC2</version>
		</dependency>

JettyTest.java
作为最基本的http服务器

public class JettyTest {
	public static void main(String[] args) throws Exception {
		Server server = new Server(8081);
		HandlerWrapper handler = new HandlerWrapper() {
			@Override
			public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
					throws IOException, ServletException {
				response.getWriter().print("hello...");
				response.flushBuffer();//一定要flush,否则数据不会写出去
			}
		};
		server.setHandler(handler);
		server.start();
		server.join();
	}
}

如果想整合spring,那么参考
JettySpringMVCStart.java

public class JettySpringMVCStart {

	public static final int PORT = 8080;

	// web访问的根路径http://ip:port/,相当于项目名,/即忽略项目名
	public static final String CONTEXT_PATH= "/";

	private static final String DEFAULT_WEBAPP_PATH = "src/main/webapp";

	public static Server createServerIn(int port) {
		// 创建Server
		Server server = new Server(port);

		WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, CONTEXT_PATH);
		//webContext.setDescriptor(DEFAULT_WEBAPP_PATH+"/WEB-INF/web.xml");
		//webContext.setResourceBase(DEFAULT_WEBAPP_PATH);
		//webContext.setClassLoader(Thread.currentThread().getContextClassLoader());
		//server.setHandler(webContext);
		server.insertHandler(webContext);
		return server;
	}

	public static void main(String[] args) throws Exception {
		//DOMConfigurator.configure(Thread.currentThread().getContextClassLoader().getResource("log4j.xml"));
		Server server = createServerIn(PORT);
		server.stop();
		server.start();
		server.join();
	}
}

用代码的方式,通过main方法启动web app。
有没有一点spring boot的感觉?
一个非常大的实际的好处,是启动时间比部署到tomcat快很多。在我的场景,用tomcat启动52秒,用jetty启动22秒。开发效率提升了有木有?

猜你喜欢

转载自blog.csdn.net/zhoujiaping123/article/details/83036443