Save the picture in my webApps' resources directory and the simply reference it at xhtml page. But unfortunately don't get the webApps's directory to save it there. How to do so?
Technically, you can use ExternalContext#getRealPath() to convert a relative web path to an absolute disk file system path.
String relativeWebPath = "/upload";
String absoluteDiskPath = externalContext.getRealPath(relativeWebPath);
File file = File.createTempFile(prefix + "_", "." + suffix, new File(absoluteDiskPath));
// ...
But this is not recommended! Whenever you write files to public webcontent, they will all get lost whenever you redeploy the webapp or even when you restart the server. It's not intented as permanent storage. Check How to save uploaded file in JSF for the right way.
I save the picture outside my webapp (as shown in the example). But then I have to reference an external image into xhtml pages, which I also don't know how to do.
Either add the path as new context of the server (how to do this depends on the servletcontainer make/version, or create a servlet which just gets an InputStream
of it by FileInputStream
and writes it to the OutputStream
of the response. See also Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag.