Embedded Jetty找不到Annotated Servlet

时间:2014-09-04 20:12:06

标签: java servlets annotations jetty embedded-jetty

短: 我有一个提供war工件的项目,其中包含一个带注释但没有web.xml的servlet。如果我尝试在jetty中使用war,我总是只获得war内容的目录列表,而不是servlet执行。

有什么想法吗?

长篇故事: 我的servlet看起来像这样

package swa;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet( asyncSupported = false, urlPatterns={"/*"})
public class ServletX extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html");

        // Actual logic goes here.
        PrintWriter out = response.getWriter();
        out.println("<h1>Hi there..</h1>");
    }

}

所以我猜没什么特别的。当我使用mvn jetty:run时,一切都很好。确保这一点后,项目将被打包成一个战争档案。

此war存档在另一个必须在代码中设置jetty的项目中使用。这就是它的完成方式:

        String jettyPort = properties.getProperty("jetty.port", "8080");
        Server server = new Server();

        ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory());
        httpConnector.setPort(Integer.parseInt(jettyPort));
        httpConnector.setAcceptQueueSize(2);
        httpConnector.setHost("0.0.0.0");
        httpConnector.setIdleTimeout(30000);
        server.setConnectors(new Connector[] { httpConnector });

        WebAppContext wacHandler = new WebAppContext();
        wacHandler.setContextPath("/admin");
        wacHandler.setWar("swa-0.0.1-SNAPSHOT.war");
        wacHandler.setConfigurationDiscovered(true);

        server.setHandler(wacHandler);

        server.start();

执行此项目时,日志告诉我发现了战争。但是如果我打开网址http://localhost:8080/admin我只会看到战争内容的列表(而不是&#39;嗨那里&#39;)。

有人能指出我的失败吗?

2 个答案:

答案 0 :(得分:5)

您需要适当地(并以正确的顺序)定义WebAppContext配置。

    wacHandler.setConfigurations(new Configuration[]
    { 
        new AnnotationConfiguration(), 
        new WebInfConfiguration(), 
        new WebXmlConfiguration(), 
        new MetaInfConfiguration(), 
        new FragmentConfiguration(),
        new EnvConfiguration(), 
        new PlusConfiguration(), 
        new JettyWebXmlConfiguration() 
    });

不要忘记添加jetty-annotations.jar

这是EmbedMe.java一起使用的示例,其中使用的是Servlet 3.1

https://github.com/jetty-project/embedded-servlet-3.1/

答案 1 :(得分:2)

除了添加上述答案中所述的必要配置外,还需要强制Jetty扫描当前项目编译的类,Jetty默认忽略这些类。为此,只需在WebAppContext上调用以下内容:

context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/classes/.*")

请参阅此处的完整示例(在Kotlin中):https://github.com/mvysny/vaadin-on-kotlin/blob/master/vok-example-crud/src/test/java/com/github/vok/example/crud/Server.kt

这很棒,可以发现所有@WebServlets,@ WebListeners等。