简体   繁体   中英

Images are not being displayed properly over JSP

I am trying to develop a website in which images related to a particular entity are displayed over a JSP when we select that entity from a drop-down over a previous JSP.I am fetching images from MySQL database. I have tried to deploy my application in both Oracle Weblogic 12c and Apache Tomcat 7.x. and I am facing almost similar type of problems with both.

A. Weblogic - Only one image used to be displayed(in case if there are multiple images related to that drop-down in database) and that also in very first attempt. For rest of attempts I am getting below error :

java.net.ProtocolException: Didn't meet stated Content-Length, wrote: '0' bytes instead of stated

Condition 1 : Only one image being displayed(on first time accessing app time since started server) even if there are multiple images related to a particular drop-down

Condition 2 : If I go back by browser back button or again hitting URL(irrespective of browser) nothing is being displayed until and unless I am not restarting server

A. Tomcat - Story is slightly different in case of Tomcat.I am not getting exception over console in case of Tomcat

Condition 1 : Only one image being displayed(on first time accessing app time since started server) even if there are multiple images related to a particular drop-down. rest all images used to be shown as broken for couple for seconds until page loads completely.When page loads completely only one image used to be there(First one) and rest all broken images used to be disappeared

Condition 2 : If I go back by browser back button or again hitting URL(irrespective of browser) without restarting server all images used to be shown as broken and used to be disappeared when page loads completely

With Tomcat image displaying page used to be hang for almost 5-10 seconds

relevant code snippets have been given below :

MultiimageServlet.java

package com.ankit.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import com.ankit.dao.ImageDAO;

public class MultiImageservlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public MultiImageservlet() {
    super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try
    {
        int bufferSize = 8192;
    BufferedInputStream input1 =null;
    BufferedOutputStream output =null;
    InputStream input =null;
    java.net.URL url1=Thread.currentThread().getContextClassLoader().getResource("Log4j.xml");
    DOMConfigurator.configure(url1);
    Logger logger = Logger.getLogger(MultiImageservlet.class);
    String imageName = request.getPathInfo().substring(1);
    logger.info("imageName "+imageName);
    List<Object> mixList = ImageDAO.find(imageName);
     input = (InputStream) mixList.get(1);
     input1 = new BufferedInputStream(input);
    logger.info("input "+input);
    Blob pic = (Blob)mixList.get(0);
    logger.info("Blob "+pic);
    int length = (int)pic.length();
    response.setContentType("image/jpg");
    response.setHeader("Content-Type", getServletContext().getMimeType(imageName));
    response.setHeader("Content-Length", String.valueOf(pic.length()));
    response.resetBuffer();
    response.setHeader("Content-Disposition", "inline; filename=\"" + imageName + "\"");
    //ServletOutputStream output = response.getOutputStream();
    output = new BufferedOutputStream(response.getOutputStream());
    byte[] buffer = new byte[bufferSize];
     while ((length = input1.read(buffer)) != -1) {                
           System.out.println("writing " + length + " bytes");                 
          output.write(buffer, 0, length);
          }


     input1.close();
      output.flush();
     output.close();
     response.flushBuffer();

    }

    catch(Exception ex)
    {

        ex.printStackTrace();
    }

}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}}

MultiImages.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org     /TR/html4/loose.dtd">
<%@ page import ="org.apache.log4j.*" %>
<%@ page import = "org.apache.log4j.xml.DOMConfigurator" %>
<%
int timeout = session.getMaxInactiveInterval();
response.setHeader("Refresh", timeout + "; URL = login.jsp");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>multiImages</title>
</head>
<body>
<h1> Welcome <%=session.getAttribute("userName") %> </h1>
<% java.net.URL     url1=Thread.currentThread().getContextClassLoader().getResource("Log4j.xml");
DOMConfigurator.configure(url1);
Logger logger = Logger.getLogger("multiImages.jsp");
logger.info("inside multiImages.jsp");
%>
<c:forEach items="${imageNames}" var="imageName">
<img src="MultiImageservlet/${imageName}"  height="150" width="150">
<%
logger.info("multi servlet executed");
%>
</c:forEach>
<a href="logout.jsp"><b>Logout</b></a>
</body>
</html>

Looking like buffer size problem in each of the cases.Could somebody please suggest.Almost stuck for 4-5 days over same thing.

I think that your error is caused by setting the "Content-Disposition" header. This header is used to let the browser know that a file will be downloaded in the response either as inline or as an attachment.

Anyway this is not your case if I understand the problem correctly. What you need is to create an html page with image urls <img src="MultiImageservlet/${imageName}" . The browser will make that request and expects the binary data of an image to be returned not something to download.

The headers below should be enough for the download:

response.setContentType("image/jpg");
response.setHeader("Content-Type", getServletContext().getMimeType(imageName));
response.setHeader("Content-Length", String.valueOf(pic.length()));

Please remove the lines:

response.resetBuffer();  // You shouldn't need this either
response.setHeader("Content-Disposition", "inline; filename=\"" + imageName + "\"");

If the problem persists I would suggest to try with a simple html page that would display a single image and try to debug from there.

I hope that helps

I have got answer for my question....:)

Actually data coming from ImageDAO was not flushed properly.I fixed it by clearing the mixList in multiimageServlet after each ImageDAO.find() call.

I disabled unnecessary headers also as those were not required actually.

Thanks for help , cs..:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM