2012-07-09 1 views
1

로컬 디스크에 저장된 이미지를 성공적으로 표시하려고합니다. 내 index.xhtml에서디스플레이 이미지 JSF

내가 가진 :

<!-- JSF mapping --> 
    <servlet> 
     <servlet-name>Faces Servlet</servlet-name> 
     <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>Faces Servlet</servlet-name> 
     <url-pattern>*.xhtml</url-pattern> 
    </servlet-mapping> 

    <!-- Image Mapping --> 
    <servlet> 
     <servlet-name>imageServlet</servlet-name> 
     <servlet-class>package.ImageServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>imageServlet</servlet-name> 
     <url-pattern>*.png</url-pattern> 
    </servlet-mapping> 

    <context-param> 
     <param-name>javax.faces.PROJECT_STAGE</param-name> 
     <param-value>Development</param-value> 
    </context-param> 

내가 말한 것처럼, 이미지 :

<h:graphicImage id="image" value="#{tableData.imageTitle}" /> 

내가 the tutorial

내 web.xml에 따라 새로운 서블릿을 만들었습니다 찾을 수 없습니다 (내 이미지는 "C : \ Documents and Settings \ user \ images"에 저장 됨).

모든 의견을 보내주십시오. 고맙습니다!

UPDATE :

나는 부두와 JSF 2.0를 내장 사용하고 있습니다. 이 (내가 튜토리얼에서 ImageServlet 조금 수정)처럼

내 ImageServlet 보인다 :

내 빈은 다음과 같습니다
/* 
* The Image servlet for serving from absolute path. 
*/ 
public class ImageServlet extends HttpServlet { 

    // Constants 
    // ---------------------------------------------------------------------------------- 

    private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB. 

    // Properties 
    // --------------------------------------------------------------------------------- 

    private String imagePath; 

    // Actions 
    // ------------------------------------------------------------------------------------ 

    public void init() throws ServletException { 

     // Define base path somehow. You can define it as init-param of the 
     // servlet. 
     this.imagePath = "C:\\Documents and Settings\\user\\images"; 
     //this.imagePath = PlatformConfig.getProperty("LocalOperation.Images.Path", null); 
     System.out.println("imagePath = " + imagePath); 

     // In a Windows environment with the Applicationserver running on the 
     // c: volume, the above path is exactly the same as "c:\images". 
     // In UNIX, it is just straightforward "/images". 
     // If you have stored files in the WebContent of a WAR, for example in 
     // the 
     // "/WEB-INF/images" folder, then you can retrieve the absolute path by: 
     // this.imagePath = getServletContext().getRealPath("/WEB-INF/images"); 
    } 

    protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // Get requested image by path info. 
     String requestedImage = request.getPathInfo(); 
     System.out.println("requestedImage = " + requestedImage); 

     // Check if file name is actually supplied to the request URI. 
     if (requestedImage == null) { 
      // Do your thing if the image is not supplied to the request URI. 
      // Throw an exception, or send 404, or show default/warning image, 
      // or just ignore it. 
      response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. 
      return; 
     } 

     // Decode the file name (might contain spaces and on) and prepare file 
     // object. 
     System.out.println(imagePath); 
     File image = new File(imagePath, URLDecoder.decode(requestedImage, 
       "UTF-8")); 

     // Check if file actually exists in filesystem. 
     if (!image.exists()) { 
      // Do your thing if the file appears to be non-existing. 
      // Throw an exception, or send 404, or show default/warning image, 
      // or just ignore it. 
      response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. 
      return; 
     } 

     // Get content type by filename. 
     String contentType = getServletContext().getMimeType(image.getName()); 

     // Check if file is actually an image (avoid download of other files by 
     // hackers!). 
     // For all content types, see: 
     // http://www.w3schools.com/media/media_mimeref.asp 
     if (contentType == null || !contentType.startsWith("image")) { 
      // Do your thing if the file appears not being a real image. 
      // Throw an exception, or send 404, or show default/warning image, 
      // or just ignore it. 
      response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. 
      return; 
     } 

     // Init servlet response. 
     response.reset(); 
     response.setBufferSize(DEFAULT_BUFFER_SIZE); 
     response.setContentType(contentType); 
     response.setHeader("Content-Length", String.valueOf(image.length())); 
     response.setHeader("Content-Disposition", 
       "inline; filename=\"" + image.getName() + "\""); 

     response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. 
     response.setHeader("Pragma", "no-cache"); // HTTP 1.0. 
     response.setDateHeader("Expires", 0); // Proxies. 

     // Prepare streams. 
     BufferedInputStream input = null; 
     BufferedOutputStream output = null; 

     try { 
      // Open streams. 
      input = new BufferedInputStream(new FileInputStream(image), 
        DEFAULT_BUFFER_SIZE); 
      output = new BufferedOutputStream(response.getOutputStream(), 
        DEFAULT_BUFFER_SIZE); 

      // Write file contents to response. 
      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 
      int length; 
      while ((length = input.read(buffer)) > 0) { 
       output.write(buffer, 0, length); 
      } 
     } finally { 
      // Gently close streams. 
      close(output); 
      close(input); 
     } 
    } 

    // Helpers (can be refactored to public utility class) 
    // ---------------------------------------- 

    private static void close(Closeable resource) { 
     if (resource != null) { 
      try { 
       resource.close(); 
      } catch (IOException e) { 
       // Do your thing with the exception. Print it, log it or mail 
       // it. 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

: 이미지가 왜

@ManagedBean 
@SessionScoped 
public class TableData { 

    private String imageTitle = "Image_ON.png"; 

     public String getImageTitle(){ 
     return imageTitle; 
    } 
} 

이해가 안 찾을 수 없습니다.

+0

저는 최상의 해결책은 서버를 정적 파일에 저장하는 것이라고 생각합니다. 그러나 코드를 게시하십시오. –

답변

2

서블릿을 /image/*과 같은 접두사 패턴 대신 접미사 패턴 *.png 대신 매핑 한 튜토리얼에서 찾았습니다. 이렇게하면 request.getPathInfo()은 항상 null을 반환합니다. 대신 request.getServletPath()이 필요합니다.

+0

대단히 감사합니다! 이제 작동 중입니다! – wallE

0

Virtual directory을 사용해보세요. 서블릿 등을 만들지 않고 매우 간단합니다.