图像文件未从servlet中加载到JSP中

时间:2013-08-02 21:40:41

标签: java jsp servlets

我有一个java程序,它根据发送给程序的参数生成有效的BufferedImage bi。我想从servlet调用这个程序,并让servlet向用户发送一个包含符合用户输入参数的图像的jsp。我在下面写的代码生成一个空消息而不是请求的图像。

我应该补充一点,get_bi()有时需要几百毫秒才能在我的开发计算机上生成BufferedImage。不确定问题的一部分是否是时间延迟的事情。

任何人都可以告诉我如何更改下面的代码,以便它在用户的Web浏览器中输出实际图像而不是空消息吗?

以下是ImageServlet的代码:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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 myownpackage.GetBI;

public class ImageServlet extends HttpServlet{
//   private Logger logger = Logger.getLogger(this.getClass());
   private RequestDispatcher jsp;

   public void init(ServletConfig config) throws ServletException {
      ServletContext context = config.getServletContext();
      jsp = context.getRequestDispatcher("/WEB-INF/jsp/send-image-into-html.jsp");
   }

   protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
       throws ServletException, IOException {
    //      logger.debug("doGet()");
          String imageParams = req.getParameter("imageParams");
          jsp.forward(req, resp);
   }

   protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
       throws ServletException, IOException{  
       Map<String, String> errors = validate(req);
       if (!errors.isEmpty()){
          //         logger.debug("validation errors");
          jsp.forward(req, resp);
       return;
       }

      resp.setContentType("image/gif");
      BufferedImage bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
      GetBI fetchBI = new GetBI();
      bi = fetchBI.get_bi(req.getParameter("imageParams"));
      File imgFile = new File("imgFile");
      ImageIO.write(bi, "gif", imgFile);
      resp.sendRedirect("send-image-into-html");
   }  

   public static Map<String, String> validate(HttpServletRequest req){
   HashMap<String, String> errors = new HashMap<String, String>();
   req.setAttribute("errors", errors);
   String imageParams = req.getParameter("imageParams");
   if (imageParams == null || imageParams.trim().length() == 0){
      errors.put("imageParams", "imageParams required.");
   }
   return errors;
 }
}

send-image-into-html.jsp的代码是:

<jsp:useBean id="errors" scope="request" type="java.util.Map" class="java.util.HashMap" />
<%@ include file="top.inc" %>
<%@ include file="middle.inc" %>
<table>
    <tr>
        <td width=350>
            <%=request.getParameter("imgFile")%>
            <img src="<%=request.getParameter("imgFile")%>">
        </td>
        <td>
            <form method="post">
                <table>
                    <tr>
                        <td>Image Parameters: </td>
                        <td><input type="text" name="imageParams" value="some parameters" size="50" />  
                            <% if (errors.containsKey("imageParams")) {
                            out.println("<span class=\"error\">" + errors.get("imageParams") + "</span>");
                            }%>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="submit" name="submit-button" value="Click Here" />
                        </td>
                    </tr>
                </table>
            </form>
        </td>
    </tr>
</table>
<%@ include file="bottom.inc" %>

编辑:


我根据我对Joop建议的理解编辑了我的代码,但它仍然无效。你能告诉我如何进一步编辑它以使其有效吗?

以下是FirstServlet的代码:

public class FirstServlet extends HttpServlet{
    //   private Logger logger = Logger.getLogger(this.getClass());
    private RequestDispatcher jsp;

public void init(ServletConfig config) throws ServletException {
    ServletContext context = config.getServletContext();
    jsp = context.getRequestDispatcher("/WEB-INF/jsp/send-image-into-html.jsp");
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {//      logger.debug("doGet()");
    jsp.forward(req, resp);
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException{
    Map<String, String> errors = validate(req);
    if (!errors.isEmpty()){//         logger.debug("validation errors");
        jsp.forward(req, resp);
        return;
    }
    resp.sendRedirect("/send-image-into-html");
}

public static Map<String, String> validate(HttpServletRequest req){
    HashMap<String, String> errors = new HashMap<String, String>();
    req.setAttribute("errors", errors);
    String imageParam1 = req.getParameter("imageParam1");
    if (imageParam1 == null || imageParam1.trim().length() == 0){  
        errors.put("imageParam1", "imageParam1 required.");
    }
    return errors;
}
}  

以下是SecondServlet的代码:

public class GetGraphServlet extends HttpServlet{
    //   private Logger logger = Logger.getLogger(this.getClass());
    private RequestDispatcher jsp;

public void init(ServletConfig config) throws ServletException {
    ServletContext context = config.getServletContext();
    jsp = context.getRequestDispatcher("/WEB-INF/jsp/send-image-into-html.jsp");
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {//      logger.debug("doGet()");
    // Create the BufferedImage, using any parameters and
    // possibly the exact request URI:
    String requestURI = req.getRequestURI();
    String imageParam1 = req.getParameter("imageParam1");
    resp.setContentType("image/gif");//256 colors
    BufferedImage bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
    GetBI fetchBI = new GetBI();
    bi = fetchBI.get_bi(req.getParameter(imageParam1));
    ImageIO.write(bi,"gif",resp.getOutputStream());
    resp.setContentType("image/gif"); // 256 colors.
    ImageIO.write(bi, "gif", resp.getOutputStream());
    jsp.forward(req, resp);
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException{}
}

以下是send-image-into-html.jsp

的代码
<jsp:useBean id="errors" scope="request" type="java.util.Map" class="java.util.HashMap" />
<%@ include file="top.inc" %>
<%@ include file="middle.inc" %>
    <form method="post">
        <table>
            <tr>
                <td width=350>
                    <img src="<%="/get-graph.gif?imageParam1="%>">
                </td>
                <td>
                    <table>
                        <tr>
                            <td>imageParam1: </td>
                            <td><input type="text" name="imageParam1" value="samplevalue" size="50" />
                            <%if (errors.containsKey("imageParam1")) {
                                out.println("<span class=\"error\">" + errors.get("imageParam1") + "</span>");}%>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="submit" name="submit-button" value="CreateImage"/>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </form>
<%@ include file="bottom.inc" %>  

以下是web.xml中的相关标签:

    <servlet>
        <servlet-name>FirstServlet</servlet-name>
            <servlet-class>mypackage.FirstServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FirstServlet</servlet-name>
            <url-pattern>/html-page-url</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>SecondServlet</servlet-name>
        <servlet-class>mypackage.SecondServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SecondServlet</servlet-name>
        <url-pattern>/get-graph</url-pattern>
    </servlet-mapping>

3 个答案:

答案 0 :(得分:1)

使用getRealPath进行文件转换的Web应用程序路径。

  File imgFile = req.getServletContext().getRealPath("/images/generated.gif");

  <img src="/images/generated.gif?t=<%= imgFile.lastModified() %>">

添加虚拟参数t=...以防止缓存。

由于重定向(对HTML!)而不是:

  //resp.setContentType("image/gif");
  //resp.setContentLength((int)imgFile.length());

你也可以在img.src中输入servlet URL,以便在没有文件的情况下即时生成图像:

  resp.setContentType("image/gif");
  ImageIO.write(bi, "gif", resp.getOutputStream());

创建一个单独的图像生成servlet,该servlet在响应的输出流上返回图像的二进制数据。 <img src="...?imageParam1=...&">的src URL映射在此servlet上。

<img src=".../... .gif?imageParam1=...&imageParam2=...">

protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {

       // Create the BufferedImage, using any parameters and
       // possibly the exact request URI:
       String requestURI = req.getRequestURI();
       String imageParam1 = req.getParameter("imageParam1");
       String imageParam2 = req.getParameter("imageParam2");

       BufferedImage bi = ...

       resp.setContentType("image/gif"); // 256 colors.
       ImageIO.write(bi, "gif", resp.getOutputStream());
}

答案 1 :(得分:1)

看起来您有3个单独的请求:

  1. 获取html-page-url

    (以send-image-into-html.jsp(包含表格)回复)。

  2. 使用参数imageParam1 = ...

    发布html-page-url

    (用send-image-into-html.jsp(包含图片)回复)。

  3. 使用参数imageParam1 = ...

    获取get-graph.gif

    (用gif内容类型和图像数据回复)。

  4. 重要的是缩小问题所在并逐一解决。将完整日志记录添加到servlet并使用FireBug / Chrome DevTools之类的工具来查看正在发生的事情。查看请求,参数和生成的html。哪些网址正确?哪些参数正确?哪些回答是正确的?

    我认为第一个请求工作正常。

    从第三个请求开始。这可以通过直接在浏览器中输入URL来自行测试。检查是否需要.gif扩展名和完整路径。

    您至少需要删除重复的行和jsp.forward:

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
        // Create the BufferedImage, using any parameters and
        // possibly the exact request URI:
        String requestURI = req.getRequestURI();
        String imageParam1 = req.getParameter("imageParam1");
        BufferedImage bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
        GetBI fetchBI = new GetBI();
        bi = fetchBI.get_bi(req.getParameter(imageParam1));
    
        resp.setContentType("image/gif");//256 colors
        ImageIO.write(bi,"gif",resp.getOutputStream());
    }
    

    正确显示图像后,请测试包含图像的页面。你现在知道了url应该是什么,所以看看生成的html并将它与你期望的进行比较。图像src是否正确?

    <td width=350>
        <img src="<%="/get-graph.gif?imageParam1="%>">
    </td>
    

    看起来它使用绝对路径和扩展名,不输出任何参数值,即使用户没有输入imageParam也会显示。

    因此需要在此处输出imageParam1参数的值,可能在其周围使用if语句。您现在可以像在其他地方一样使用scriplet,但是您应该考虑使用像jstl这样的标记库。

    修改

    我没有GetBI类,但我测试了这个例子:

    public class SecondServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String imageParam1 = request.getParameter("imageParam1");
    
            BufferedImage bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
    
            // Try replacing with:
            //GetBI fetchBI = new GetBI();
            //BufferedImage bi = fetchBI.get_bi(req.getParameter("imageParam1"));
    
            Graphics2D g = bi.createGraphics();
            g.setColor(new Color(255, 255, 255));
            g.drawString(imageParam1, 0, 150);
            g.dispose();
    
            response.setContentType("image/gif");
            ImageIO.write(bi, "gif", response.getOutputStream());
        }
    }
    

    这将显示imageParam1文本的图像:

    http://127.0.0.1:8080/myapp/get-graph?imageParam1=Testing
    

答案 2 :(得分:0)

试试这个......它可以100%运行

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author kites
 */
public class FileUpload extends HttpServlet {

    File uploadFile;
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    long fileSize;


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            boolean bb = upload(request);


        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private boolean upload(HttpServletRequest request) {
        boolean bool = false;

        try {
                    String fileName = "";

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                System.out.println("Inside fileupload.....");
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                //  System.out.println("File content" + request.getParameter("f1"));
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    FileItem item1 = item;
                    System.out.println("Form field:::" + item.isFormField());

                    if (!item.isFormField()) {
                        fileName = item.getName();
                        fileSize = item.getSize();
                        File f = new File("C:\\"+fileName);
                        String filepath=f.getAbsolutePath();

                        System.out.println("fileName = " + fileName);
                        System.out.println("fileSize = " + fileSize);
                        if (!fileName.equals("")) {


                            item.write(filepath);


                        }
                    }


                }


            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }


}