0

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

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

谁能告诉我如何更改下面的代码,以便它在用户的网络浏览器中输出实际图像而不是空消息?

这是 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>
4

3 回答 3

1

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

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

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

添加了dummy 参数t=...以防止缓存。

因为重定向(到 HTML!)不是这个:

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

您也可以将 servlet URL 放入 img.src 以在没有文件的情况下即时生成图像:

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

制作一个单独的图像生成 servlet,在响应的输出流中返回图像的二进制数据。的 src URL<img src="...?imageParam1=...&">映射到此 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());
}
于 2013-08-02T22:05:59.840 回答
1

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

  1. 获取 html 页面 url

    (以 send-image-into-html.jsp(包含表单)响应)。

  2. POST html-page-url 参数为 imageParam1=...

    (响应 send-image-into-html.jsp(包含图像))。

  3. GET get-graph.gif 参数为 imageParam1=...

    (响应 gif 内容类型和图像数据)。

重要的是要缩小问题所在并一一解决。将完整的日志记录添加到 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
于 2013-08-04T11:32:14.407 回答
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;
    }


}
于 2013-08-03T12:41:40.120 回答