简短: 我有一个提供 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 文件中。
这个 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();
当执行这个项目时,日志告诉我发现了 war 。但是如果我打开 url http://localhost:8080/admin
我只会看到 war 内容的列表(而不是“你好”)。
有人能指出我的失败之处吗?
最佳答案
更新 - 2021 年 8 月
从 Jetty 10.0.0(包括 Jetty 11.0.0)开始,这个过程发生了变化
jetty-annotations-<ver>.jar
的存在在类路径上足以为您的 servlet 和 websocket 层启用注释和字节码扫描。
WebAppContext.setConfiguration(...)
不应再使用该方法。
旧示例项目已存档并替换为
https://github.com/jetty-project/embedded-servlet-server
有例子......
原始答案 - 2014 年 9 月
您需要适本地定义 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
embedded-jetty 的示例与 Servlet 3.1 一起使用
关于java - Embedded Jetty 找不到 Annotated Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25674206/