我正在尝试注册本地路径资源(OSGi bundle 之外),但它不起作用。 这很奇怪,因为你还能如何使用 jar 中不存在的资源呢?
这是我的代码:
protected void bindHttpService(HttpService httpService)
{
httpService.registerResources("/testServer/resources", "/resources", null);
httpService.registerResources("/testServer/pictures", "C:\\mypath\\config\\", null);
第一个工作完美(但资源不能更改,因为它们在 jar 中),但如果我放置本地路径,它只会忽略它并返回“未找到”。
最佳答案
我使用了一个在 httpService 中注册的单独的 servlet:
httpService.registerServlet("/testServer/pictures", new ImageServlet("C:\myPics\pics"), null, null);
servlet 是我很快找到的一些代码,因此它可能不是最好的实现:
public class ImageServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private String imgPath;
public ImageServlet(String picPath){
super();
imgPath = picPath;
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletContext cntx= req.getServletContext();
// Get the absolute path of the image
// retrieve mimeType dynamically
String filename = imgPath+ "/testpicture2.jpg";
String mime = cntx.getMimeType(imgPath+ "/testpicture2.jpg");
if (mime == null) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mime);
File file = new File(filename);
resp.setContentLength((int)file.length());
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
out.close();
in.close();
}
我仍然想知道如何使用绝对路径获取本地资源而不使用此解决方法(在另一个答案中建议),因此如果您仍然可以帮助我,那就太好了!
关于java - 本地路径的 OSGi httpService.registerResources(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59134961/