我有一个在嵌入式Tomcat上运行并使用Jersey的应用程序。
有一个资源类,它公开了一些端点,如本教程http://www.sortedset.com/embedded-tomcat-jersey/所示。
一切正常,现在我想使用一种端点方法来输出格式化的文本。
我在资源中的方法如下:
@Path("/res")
@GET
@Produces("text/html")
public String get(){
return "<html><head><link rel='stylesheet' href='/style.css'></head><body>some text</body></html>";
}
}
我将style.css放在WebContent文件夹中。
当我访问资源时,文本将按预期显示,但是指向.css文件的链接似乎无效。
可能是什么问题?
更新
在Paul在评论中提出建议之后,我尝试将servlet上下文路径添加为URL路径,但是它仍然不起作用
1)
@Path("/res")
@GET
@Produces("text/html")
public String get(@Context ServletContext ctx) {
String ctxPath = ctx.getContextPath();
return "<html><head><link rel='stylesheet' href='+"ctxPath"+/style.css'></head><body>some text</body></html>";
}
}
2)
String ctxPath = ctx.getRealPath("/");
return "<html><head><link rel='stylesheet' href='+"ctxPath"+style.css'></head><body>some text</body></html>";
更新
由于问题可能出在这里,所以这是Main类的一部分,在那里我启动嵌入式Tomcat并设置Web应用程序
public void start() {
String webappDirLocation = "WebContent/"
Tomcat tomcat = new Tomcat();
tomcat.setPort(0);
Context ctx = tomcat.addWebApp("", new File(webappDirLocation).getAbsolutePath());
Tomcat.addServlet(ctx, "jersey-container-servlet", resourceConfig()).addMapping("/*");
//start tomcat
}
private ServletContainer resourceConfig() {
return new ServletContainer(new ResourceConfig(new ResourceLoader().getClasses()));
}