我在下面创建了嵌入式jetty服务器。它成功地从[host]:[port]:/ api /
服务我的REST API我现在有一个Angular应用程序除了API之外我还要提供服务,如何更新代码以便服务器提供应用程序的index.html文件?在尝试了几种不同的方法之后,我发现我的理解是缺乏的,我无法适应我所看到的例子。我们将非常感激地提出任何建议或意见。谢谢!
public class JettyServer {
private static final String API_PREFIX = "/api/*";
private static final String RESOURCE_PACKAGES_TO_SCAN = "org.brewtraption.rest";
Logger logger = LoggerFactory.getLogger(JettyServer.class);
private JettyServerConfig config = null;
public JettyServer(final JettyServerConfig config) {
this.config = config;
}
public void start() {
InetSocketAddress socket = new InetSocketAddress(config.getHost(), config.getPort());
Server server = new Server(socket);
ServletHolder servletHolder = configureAPIResources();
ServletContextHandler context = configureServletContextHandler(server, servletHolder);
initaliseWebSocketContainer(context);
startBrewtraptionServer(server);
}
private void startBrewtraptionServer(Server server) {
try {
server.start();
server.join();
} catch (Exception e) {
String message = "Unable to start Brewtraption Server. %s %s";
logger.error(String.format(message, e.getClass().getName(), e.getMessage()));
}
}
private void initaliseWebSocketContainer(ServletContextHandler context) {
try {
ServerContainer container = WebSocketServerContainerInitializer.configureContext(context);
container.addEndpoint(EventSocket.class);
} catch (ServletException | DeploymentException e) {
String message = "Unable to create ServerContainer. %s %s";
logger.error(String.format(message, e.getClass().getName(), e.getMessage()));
}
}
private ServletContextHandler configureServletContextHandler(Server server, ServletHolder servletHolder) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(servletHolder, API_PREFIX);
FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);
filterHolder.setInitParameter("allowedOrigins", "*");
filterHolder.setInitParameter("allowedMethods", "GET, POST, PUT");
context.addFilter(filterHolder, "/*", null);
server.setHandler(context);
return context;
}
private ServletHolder configureAPIResources() {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.packages(RESOURCE_PACKAGES_TO_SCAN)
.register(JacksonFeature.class);
ServletContainer servletContainer = new ServletContainer(resourceConfig);
return new ServletHolder(servletContainer);
}
}
答案 0 :(得分:1)
你需要两件事。
context.setWelcomeFiles(new String[] { "index.html", "index.htm", "index.jsp" });
// Lastly, the default servlet for root content (always needed, to satisfy servlet spec)
// It is important that this is last.
ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
holderPwd.setInitParameter("resourceBase",pwdPath);
holderPwd.setInitParameter("dirAllowed","true");
context.addServlet(holderPwd,"/");