前提
已经安装了本地maven库和eclipse中的maven插件。
构建步骤
(一)创建Maven项目
(1)菜单New——>Project…->Maven Project
(2)选择下一步,在Archetype中选择maven-archetype-webapp
(3)点击下一步
Group Id 中输入项目的基本包名。
Artifact Id 中输入项目名。
Version 中的值默认就行,不进行选择。
Package 中写的是默认生成的一个包名,不写也可以。
接着点击完成就可以了。
(二)Maven项目配置
(1)在pom.xml 里面build 标签下添加 maven编译插件。
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
(2)在pom.xml中添加Jetty依赖。
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jsp</artifactId>
<version>8.2.0.v20160908</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all-server</artifactId>
<version>8.2.0.v20160908</version>
</dependency>
(3)添加缺少的目录并指定输出路径
Maven规定,必须创建以下几个包,并且分别对应相应的输出路径
src/main/resources
src/main/java
src/test/resources
src/test/java
默认仅创建了src/main/resources文件夹,需要手动创建其他三个文件夹。
右键项目----->Properties----->Java Build Path----->Source,点击Add Folder… 添加缺少的目录,并将src/test/resources和src/test/java的输出目录改为 target/test-classes (双击Output folder)进行更改。
(三)创建Jetty Server主类
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class Main {
public static void main(String[] args) {
// 服务器的监听端口
Server server = new Server(8000);
// 关联一个已经存在的上下文
WebAppContext context = new WebAppContext();
// 设置描述符位置
context.setDescriptor("./src/main/webapp/WEB-INF/web.xml");
// 设置Web内容上下文路径
context.setResourceBase("./src/main/webapp");
// 设置上下文路径
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.setStopAtShutdown(true);
try {
server.start();
System.out.println("Jetty-8.2.0 Server war started");
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
(四)测试
默认项目的src/main/webapp下有一个JSP文件index.jsp,内容如下:
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
运行Jetty Server主类,并用浏览器访问9000端口,显示结果如下:
若显示错误There is an error in invoking javac. A full JDK (not just JRE) is required。则需要把运行的JRE改为JDK,
方法右键Jetty Server主类 Run As…----->Run Configurations… 进入配置界面
点击“Installed JREs”
点击“Add”
然后选择JDK的安装目录,点击“Finish”
然后选择刚添加的JDK,单击Apply and Close,完成。