这在过去的两天里一直困扰着我。我的问题是我已经使用嵌入式码头开发了jax-rs Web服务,并且作为一个独立的项目完全可以正常工作。当我尝试调用通过其他代码的反射启动码头服务器的主要方法。我已经交叉检查了是否没有类加载器问题(显然没有抛出错误),但是我访问Web服务的路径返回了404,没有抛出错误。我从日志中可以看到服务器正在启动很好,但其余端点未被命中或未解决,或者是404的原因是什么。还请注意,该项目的依赖jar以及包含main方法的类是通过从url创建的url类加载器加载的源文件和jar。迫切需要帮助
启动码头服务器的代码
public void startJettyServer(){
try {
/* code to enable logging in jetty */
StdErrLog logger = new StdErrLog();
logger.setLevel(1);
Log.setLog(logger);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
/*
* code to enable startup listeners StartupListener sup=new
* StartupListener(); context.addEventListener(sup);
*/
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
//jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
//org.demonking.JettyServiceApp.class.getCanonicalName());
jerseyServlet.setInitParameter("jersey.config.server.provider.packages",
"org.demonking");
System.out.println("i am here");
jettyServer.start();
// jettyServer.join();
// jettyServer.stop();
} catch (Exception e) {
e.printStackTrace();
} finally {
// jettyServer.destroy();
}
}
调用此方法的代码
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
try
{
AppServer appServer = new AppServer();
appServer.startJettyServer();
System.out.println("exiting main");
} catch (Exception ex)
{
System.out.println("in exception in app class");
ex.printStackTrace();
}
}
通过反射调用main方法的代码
List<URL> urlsR = new ArrayList<URL>();
//location of source files
File file = new File("C:\\Users\\DemonKing\\Documents\\eclipseprojects\\JettyDemo\\bin\\");
// convert the file to URL format
URL url = file.toURI().toURL();
urlsR.add(url);
//location of dependent jars
File file2 = new File("F:\\JettyJarsComplete");
for (File child : file2.listFiles()) {
File resFile = new File(file2 + "\\" + child.getName());
System.out.println(resFile);
URL url2 = resFile.toURI().toURL();
urlsR.add(url2);
}
URL[] urls = urlsR.toArray(new URL[urlsR.size()]);
// load this folder into Class loader
ClassLoader cl = new URLClassLoader(urls);
Class<?> cls = cl.loadClass("org.demonking.App");
Method m = cls.getDeclaredMethod("main", String[].class);
m.invoke(null, (Object) null);