gpt4 book ai didi

java - 具有带注释的 servlet 模式的嵌入式 Jetty?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:51 25 4
gpt4 key购买 nike

以下工作代码演示了将两个 servlet 包含到 jetty 的嵌入式实例中。

Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(new ServletHolder(new Html()), "/html");
context.addServlet(new ServletHolder(new Iphone()), "/iphone");
server.setHandler(context);
server.start();
server.join();

应该如何更改它以便不使用 url“/iphone”,而是使用 servlet 注释中的 urlpatterns,即

@WebServlet(urlPatterns={"/json", "/iphone"})
public class Iphone extends HttpServlet {
....
}

最佳答案

servlet 位于服务器的类路径中,而不是打包在 WAR 中。

Servlet 3.0 specification状态:

In a web application, classes using annotations will have their annotations processed only if they are located in the WEB-INF/classes directory, or if they are packaged in a jar file located in WEB-INF/lib within the application.

The web application deployment descriptor contains a new “metadata-complete” attribute on the web-app element. The “metadata-complete” attribute defines whether the web descriptor is complete, or whether the class files of the jar file should be examined for annotations and web fragments at deployment time. If “metadata-complete” is set to "true", the deployment tool MUST ignore any servlet annotations present in the class files of the application and web fragments. If the metadata-complete attribute is not specified or is set to "false", the deployment tool must examine the class files of the application for annotations, and scan for web fragments.

您可能需要考虑打包 WAR 并使用具有更多功能的上下文,例如 WebAppContext .

或者,您可以尝试自己的注释扫描。形式的东西:

void registerServlets(ServletContextHandler context,
Class<? extends HttpServlet> type)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
WebServlet info = type.getAnnotation(WebServlet.class);
for (String pattern : info.urlPatterns()) {
HttpServlet servlet = type.getConstructor().newInstance();
context.addServlet(new ServletHolder(servlet), pattern);
}
}

关于java - 具有带注释的 servlet 模式的嵌入式 Jetty?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13952661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com