java - 本地路径的 OSGi httpService.registerResources()

标签 java http server osgi httpservice

我正在尝试注册本地路径资源(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/

相关文章:

node.js - 两个http请求能走到一起吗?如果可以,nodeJS 服务器如何处理它?

python - 自动运行脚本时出现 Powershell 错误

java - 为什么我的服务器停止响应并且有办法监控它吗?

php - 如何通过php、swift将服务器上的图像显示到iOS设备

http - Cloudtrax HTTP 身份验证 API 调试

python - 在 Python 中将表单主体转换为字典

java - 通过 Spring Boot 仅在 Release 内(仅最后更新文件)进行可重复迁移

java - 如何查找学生Bydate (findByDate)

java - 加载带有换行符的文件

java - 使用 JOptionPane.YES_NO_OPTIONS