我正在学习Java EE 7 Servlets,并尝试使用嵌入式Jetty(v 9.3.7)从Java EE 7教程部署hello2
example,但收效甚微。 hello2
由两个servlet和一个图像文件组成。该配置被注释并且该项目没有任何web.xml。使用带注释的配置文件的嵌入式码头
继WebAppContext
部分从嵌入码头examples我创造了这个主类以启动我的嵌入式服务器:
public class MyServer {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
String webappPath = new File(MyServer.class.getProtectionDomain().getCodeSource().getLocation().getFile())
.getParentFile().getParentFile().getAbsolutePath();
WebAppContext webapp = new WebAppContext(webappPath, "");
webapp.setConfigurations(new Configuration[]{
new AnnotationConfiguration()});
server.setHandler(webapp);
server.start();
server.join();
}
}
据我了解,由于码头是一个Java EE Web容器,它应该能够服务于示例Serlvet项目是,我只需要指向战争文件夹结构。以下是该项目的结构:
-- hello2
\-- src
\-- main
+-- java
│ +-- MyServer.java
│ \-- javaeetutorial
│ \-- hello2
│ +-- GreetingServlet.java
│ \-- ResponseServlet.java
\-- webapp
+-- WEB-INF
│ \-- classes
│ +-- MyServer.class
│ \-- javaeetutorial
│ \-- hello2
│ +-- GreetingServlet.class
│ \-- ResponseServlet.class
+-- index.html
\-- resources
\-- images
\-- duke.waving.gif
的hello2
示例代码可以发现here。以下是该文件被编译为hello2/webapp/classes/
从而使webapp
文件夹的分解WAR的GreetingServlet
@WebServlet("/greeting")
public class GreetingServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
....
和ResponseServlet
@WebServlet("/response")
public class ResponseServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
....
某些部分。我添加index.html是为了测试Jetty是否选择它。其结果是,我得到404错误当我访问本地主机:8080,本地主机:8080 /问候或本地主机:8080 /响应
如果我添加WebXmlConfiguration
与webapp.setConfigurations()
,然后设置类似webapp.setResourceBase(webappPath)
的资源基础,我设法进入Jetty的静态文件服务器。这是因为Jetty然后使用默认的web.xml
,它将用于文件服务目的的servlet添加到服务器。但即使如此,我的注释servlet没有拿起。
我有码头阅读注释servlet配置是通过设置WEB-INF
目录的方式明确使用WebAppContext.getMetadata().setWebInfClassesDirs()
:
webapp.getMetaData().setWebInfClassesDirs(
Arrays.asList(Resource.newResource(
MyServer.class.getProtectionDomain().getCodeSource().getLocation())));
然后,servlet的反应不如预期,但这并不为我的index.html
或图像文件。我也将资源库设置为无用。所以我想要的是Jetty无需web.xml
即可为我的Web应用程序提供服务,并且只需将它指向展开的WAR目录即可。显然我错过了一些东西。
正如我在我的问题中写的,我使用注释来配置,而不是在Java EE 7中可选的web.xml。另外,我相信我不需要WEB-INF/lib,因为我没有使用它。我只使用了AnnotationConfiguration,因为我配置了注释中的所有内容,我想了解它为什么不起作用。我的理论是,这个设置应该适用于所有支持servlet容器的Java EE 7。 – qtips
即使您没有实际的文件,您仍然需要配置,因为这是如何设置webapp元数据的。没有配置,没有元数据,没有关于设置的知识,等等。元数据是构建在所有这些配置上的。只有Annotation/Plus/Env是可选的,其余都是必需的。 –
添加WebInfConfiguration时,Jetty开始阅读我的注释配置:)我仍然认为我不应该需要WebXmlConfiguration,因为我看到Jetty使用默认的web.xml来设置一些内置的servlet。但没有它,Jetty不会服务我的index.html。为什么必须添加自己的web.xml以支持静态内容?我想我被Jettys WebAppContext弄糊涂了;它用于专门为Web应用程序提供服务(与ServletContextHandler相比),但不支持标准的Java EE配置,不使用setConfigurations。 – qtips