Retrieve the web app root path in JSF Managed Bean

后端 未结 4 1728
梦谈多话
梦谈多话 2021-01-02 08:50

Im trying to access the example/web folder (see below in the image) in a jsf managed bean but cant seem to find a way to do it

4条回答
  •  自闭症患者
    2021-01-02 09:32

    Just wanted to thank Balus C. Code Java with JSP, in Tomcat/Tomee server I the following code that works:

    private Boolean SaveUserItemImage(Part ui, String bid) throws IOException {
    
        Boolean fileCreate = false;
        OutputStream out = null;
        InputStream filecontent = null;
        ExternalContext ctx = context().getExternalContext();
        String absoluteWebPath = ctx.getRealPath("/");
        String resource_path = absoluteWebPath + "\\resources\\";
        String image_path = resource_path + "\\" + this.itemType + "_images\\";
        String buildFileName = image_path + bid + "_" + getFileName(ui);
        File files = null;
    
        try {
          files = new File(buildFileName);
          fileCreate = true;
        } catch (Exception ex) {
          System.out.println("Error in Creating New File");
          Logger.getLogger(ItemBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    
        if (fileCreate == true) {
          if (files.exists()) {
            /// User may be using same image file name but has been editted
            files.delete();
          }
    
          try {
            out = new FileOutputStream(files);
            filecontent = ui.getInputStream();
            int read = 0;
            final byte[] bytes = new byte[1024];
            while ((read = filecontent.read(bytes)) != -1) {
              out.write(bytes, 0, read);
            }
            fileCreate = true;
          } catch (FileNotFoundException fne) {
            fileCreate = false;
            Logger.getLogger(ItemBean.class.getName()).log(Level.SEVERE, "SaveUserItemImage", fne);
          } finally {
            if (out != null) {
              out.close();
            }
            if (filecontent != null) {
              filecontent.close();
            }
            files = null;
          }
        }
        return fileCreate;
      }
    

提交回复
热议问题