A.综述
Jetty 一个servlet 容器与Tomcat 相同。不同的是Jetty比Tomcat更加“小”--轻量级容器。这句话的意思是,jetty可作为webApp项目的一部分嵌入的web项目中。目前我了解到的Jetty的使用方式有两种:
1.下载Jetty包,运行start.jar。这是将Jetty作为一个独立的软件(服务器软件与tomcat的使用相似)来使用。
2.下载jetty的库(jar包),引入到web项目中,编写启动类作为服务器使用。
注:以上两种方式都的目的是相同:Jetty是java语言实现的服务器软件(或者库)。不同的是两种实现手段不同。
当然还有别的用途,这个以后遇到了,再补充。
B.分述
1.下载jetty包,运行start.jar
下载路径:jetty 7.5.0下载路径
解压后目录:
双击或者DOS下运行start.jar就可以了。通过命令 netstat -ano|findstr 8080 查看启动情况
2.编写自启动类,运行web项目
2.1首先引入依赖包:
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all</artifactId>
<version>9.2.14.v20151106</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jsp</artifactId>
<version>9.2.15.v20160210</version>
</dependency>
2.2编写启动类
import javax.websocket.server.ServerContainer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
//import org.slf4j.helpers.MessageFormatter;
/**
* web 项目引入jetty
* 1.编写jetty的自启动类--这种启动类没有问题。web访问正常
* @author phda
*
*/
public class Main {
public static void main(String[] args) {
System.out.println("this is main class");
int port = 8080;
Server server = new Server(port);
WebAppContext webAppContext = new WebAppContext("webapp","/TestWeb");
webAppContext.setDescriptor("webapp/WEB-INF/web.xml");
webAppContext.setResourceBase("src/main/webapp");
webAppContext.setDisplayName("TestWeb");
webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader());
webAppContext.setConfigurationDiscovered(true);
webAppContext.setParentLoaderPriority(true);
//MessageFormatter.arrayFormat(arg0, arg1)
server.setHandler(webAppContext);
System.out.println(webAppContext.getContextPath());
System.out.println(webAppContext.getDescriptor());
System.out.println(webAppContext.getResourceBase());
System.out.println(webAppContext.getBaseResource());
try {
ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(webAppContext);
// Add WebSocket endpoint to javax.websocket layer
//wscontainer.addEndpoint(MyWebSocket.class); //这行是如果需要使用websocket就加上,不需要就注释掉这行,mywebsocket是自己写的websocket服务类
server.start();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("server is start, port is "+port+"............");
}
}
启动运行,在浏览中查看运行结果:
这只是jetty的简单实用,还有更高级的配置,以后再述。