简体   繁体   English

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

[英]image file not loading in JSP from servlet

I have a java program that generates a valid BufferedImage bi based on parameters that are sent to the program. 我有一个java程序,它根据发送到程序的参数生成有效的BufferedImage bi。 I want to call this program from a servlet, and have the servlet send the user a jsp containing an image that fits the parameters that the user inputs. 我想从servlet调用这个程序,并让servlet向用户发送一个包含符合用户输入参数的图像的jsp。 The code that I wrote below generates a null message instead of the requested image. 我在下面写的代码生成一个空消息而不是请求的图像。

I should add that get_bi() sometimes takes a few hundred milliseconds to produce the BufferedImage on my development computer. 我应该补充一点,get_bi()有时需要几百毫秒才能在我的开发计算机上生成BufferedImage。 Not sure if part of the problem is a time delay thing. 不确定问题的一部分是否是时间延迟的事情。

Can anyone show me how to alter the code below so that it outputs an actual image in the user's web browser instead of a null message? 任何人都可以告诉我如何更改下面的代码,以便它在用户的Web浏览器中输出实际图像而不是空消息?

Here is the code for ImageServlet: 这是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;
 }
}

The code for send-image-into-html.jsp is: 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" %>

EDIT: 编辑:


I have edited my code based on what I understand of Joop's suggestions, but it still does not work. 我根据我对Joop建议的理解编辑了我的代码,但它仍然不起作用。 Can you show me how to further edit this so that it works? 你能告诉我如何进一步编辑它以使其有效吗?

Here is the code for FirstServlet: 这是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;
}
}  

Here is the code for SecondServlet: 这是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{}
}

Here is the code for send-image-into-html.jsp 这是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" %>  

Here are the relevant tags from web.xml: 以下是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>

Use a web application path to File conversion with getRealPath . 使用带有getRealPath文件转换的Web应用程序路径。

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

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

The dummy parameter t=... is added to prevent caching. 添加伪参数t=...以防止缓存。

Because of the redirect (to HTML!) not this: 由于重定向(对HTML!)不是这样的:

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

You could alternatively also put in img.src the servlet URL to generate the image on-the-fly without file: 您也可以在img.src中输入servlet URL,以便在没有文件的情况下即时生成图像:

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

Make a separate image generating servlet that returns on the response's output stream the binary data of the image. 创建一个单独的图像生成servlet,在响应的输出流上返回图像的二进制数据。 The src URL of the <img src="...?imageParam1=...&"> is mapped on this 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());
}

It looks like you have 3 separate requests: 看起来您有3个单独的请求:

  1. GET html-page-url 获取html-page-url

    (respond with send-image-into-html.jsp (containing form)). (用send-image-into-html.jsp(包含表格)回复)。

  2. POST html-page-url with parameter imageParam1=... POST html-page-url,参数imageParam1 = ...

    (respond with send-image-into-html.jsp (containing image)). (用send-image-into-html.jsp(包含图像)回复)。

  3. GET get-graph.gif with parameter imageParam1=... 使用参数imageParam1 = G获取get-graph.gif

    (respond with gif content-type and image data). (使用gif内容类型和图像数据进行响应)。

It's important to narrow down where the problems are and tackle them one by one. 重要的是缩小问题所在并逐一解决。 Add full logging to the servlets and use a tool like FireBug/Chrome DevTools to see exactly what's happening. 将完整日志记录添加到servlet并使用FireBug / Chrome DevTools之类的工具来查看正在发生的事情。 Look at the requests, parameters and generated html. 查看请求,参数和生成的html。 Which URLs are correct? 哪些网址正确? Which parameters are correct? 哪些参数正确? Which responses are correct? 哪些回答是正确的?

I take it the first request is working fine. 我认为第一个要求是正常工作。

Start with the third request. 从第三个请求开始。 This can be tested by itself by entering the url directly in the browser. 这可以通过直接在浏览器中输入URL来自行测试。 Check whether you need the .gif extension and the full path. 检查是否需要.gif扩展名和完整路径。

You'll need to at least remove the duplicated lines and the jsp.forward: 您至少需要删除重复的行和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());
}

When the image is displayed correctly, then test the page containing the image. 正确显示图像后,请测试包含图像的页面。 You now know what the url should be so look at the generated html and compare it with what you expect. 你现在知道了url应该是什么,所以看看生成的html并将它与你期望的进行比较。 Is the image src correct? 图像src是否正确?

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

This looks like it uses an absolute path and extension, doesn't output any parameter value, and is displayed even when the user doesn't enter an imageParam. 这看起来像使用绝对路径和扩展名,不输出任何参数值,即使用户没有输入imageParam也会显示。

So the value of the imageParam1 parameter needs to be output here, probably with an if statement around it. 因此,需要在此处输出imageParam1参数的值,可能在其周围使用if语句。 You can use a scriplet for now like you've done elsewhere but you should look into using tag libraries like jstl. 您现在可以像在其他地方一样使用scriplet,但是您应该考虑使用像jstl这样的标记库。

EDIT: 编辑:

I don't have a GetBI class, but I've tested this example: 我没有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());
    }
}

This displays an image with the text of imageParam1 at: 这将显示imageParam1文本的图像:

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

Try this...it works 100% 试试这个......它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;
    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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