Tôi có webAppContext trong lớp chính và tôi có một servlet, có chú thích WebServlet và hàm dựng với args. Làm thế nào tôi có thể vượt qua args từ lớp chính để Servlet?Đối số truyền qua WebAppContext tới hàm tạo 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);
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>
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));
}
}
Bạn nên sử dụng EJB Injection khi bạn quyết định sử dụng IoC (đảo ngược kiểm soát). –