Bul*_*lat 5 java jetty servlet-3.0
我在主类中有webAppContext,我有一个servlet,它有WebServlet注释和带args的构造函数.我怎么能把args从Main类传递给Servlet?
Main.java:
String webappDirLocation = "src/main/java/frontend/webapp/";
WebAppContext webAppContext = new WebAppContext();
webAppContext.setResourceBase("public_html");
webAppContext.setContextPath("/");
webAppContext.setDescriptor(webappDirLocation + "WEB-INF/web.xml");
webAppContext.setConfigurations(new Configuration[]{
new AnnotationConfiguration(), new WebXmlConfiguration(),
new WebInfConfiguration(),
new PlusConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new EnvConfiguration()}
);
webAppContext.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/classes/.*");
webAppContext.setParentLoaderPriority(true);
Run Code Online (Sandbox Code Playgroud)
web.xml中:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="false"
version="3.0">
</web-app>
Run Code Online (Sandbox Code Playgroud)
Servlet的:
@WebServlet(name = "WebSocketGameServlet", urlPatterns = {"/gameplay"})
public class WebSocketGameServlet extends WebSocketServlet {
static final Logger logger = LogManager.getLogger(GameWebSocket.class);
private final static int IDLE_TIME = 6000 * 1000;
private AccountService accountService;
private Game game;
private WebSocketService webSocketService;
public WebSocketGameServlet(AccountService accountService, Game game, WebSocketService webSocketService) {
this.accountService = accountService;
this.game = game;
this.webSocketService = webSocketService;
}
@Override
public void configure(WebSocketServletFactory factory) {
factory.getPolicy().setIdleTimeout(IDLE_TIME);
factory.setCreator(new GameWebSocketCreator(accountService, game, webSocketService));
}
}
Run Code Online (Sandbox Code Playgroud)
嗯,据我了解,您使用 JavaSE 和嵌入式 Jetty 创建了 Web 应用程序。您可以使用注释将 servlet 添加到服务器。然后 Jetty 创建您的 servlet,它调用默认构造函数。但是您需要以某种方式将您创建的对象的链接传递main()到您的 servlet。
所以,有几种解决方案:
Map<Class<?>, Object>上下文中。并将它们放入 servlet 中。main()并由网络服务器管理。PS jetty服务器有方法addBean(...)。您可以将“bean”添加到服务器(在代码或配置中)。但据我所知,在 servlet 中获取这个 bean 是不可能的。