您可以使用请求分配器来获取图像吗?

时间:2019-01-09 16:45:13

标签: java servlets java-ee requestdispatcher

我尝试过

@WebServlet("/imgTest")
public class ImgTestServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        serveRequest(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        serveRequest(req, resp);
    }

    private void serveRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/imgs/banner.png").include(req,resp);
    }
}

那似乎行得通。

但是,如果我将serveRequest方法更改为

private void serveRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.getWriter().println("Here, have an image:");
    req.getRequestDispatcher("/imgs/banner.png").include(req,resp);
}

我得到一个

java.lang.IllegalStateException: getWriter() has already been called for this response
    org.apache.catalina.connector.Response.getOutputStream(Response.java:604)
    org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:197)
    javax.servlet.ServletResponseWrapper.getOutputStream(ServletResponseWrapper.java:96)
    org.apache.catalina.servlets.DefaultServlet.serveResource(DefaultServlet.java:877)
    org.apache.catalina.servlets.DefaultServlet.doGet(DefaultServlet.java:411)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    [...].webapp.servlets.ImgTestServlet.serveRequest(ImgTestServlet.java:24)
    [...].webapp.servlets.ImgTestServlet.doGet(ImgTestServlet.java:14)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

我不确定为什么会失败。我的猜测是请求分配器正试图仅向客户端显示图像,这与实际上嵌入较大响应中的事实不符。

所以 有一种方法可以使这项工作生效,或者我必须像这样写它

private void serveRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    resp.getWriter().println("Here, have an image:<br>");
    resp.getWriter().println("<img src='/webapp/imgs/banner.png'><br>");
}

0 个答案:

没有答案