1

我正在学习 Java Servlets,我正在使用的书有一个关于文件上传的示例,当我这样做时,我收到以下错误

HttpServletResponse 类型的方法 getInputStream() 未定义

当我尝试使用

ServletInputStream sis =  response.getInputStream();

eclipse提供的解决方案之一是

ServletInputStream sis =  ((ServletRequest) response).getInputStream();

并使用它导致以下结果

java.lang.ClassCastException: org.apache.catalina.connector.ResponseFacade 不能被强制转换

到 javax.servlet.ServletRequest ShowForm.doPost(ShowForm.java:37) javax.servlet.http.HttpServlet.service(HttpServlet.java:641) javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

这是我的完整代码:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ShowForm
 */
@WebServlet("/ShowForm")
public class ShowForm extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowForm() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();

        ServletInputStream sis =  response.getInputStream();
        for (int i = sis.read();i != -1; i = sis.read())
            {

                out.print((char)i);

            }
    }
}
4

3 回答 3

2

听听原来的错误:

HttpServletResponse 类型的方法 getInputStream() 未定义

这是在告诉你问题所在。 HttpServletResponse没有getInputStream()方法——它没有任何意义。

getInputStream()开启HttpServletRequest

当谈到自动修复建议时,Eclipse 可能有点傻。

于 2012-04-17T15:35:45.997 回答
2

那是因为ServletResponse/HttpServletResponse没有getInputStream(). 您可能实际上想要使用getInputStreamfrom HttpServletRequest

request.getInputStream()
于 2012-04-17T15:36:17.427 回答
0

您可以从 HttpServletRequest 获取 InputStream。相反,您可以从 HttpServletOutputStream 获取 OutputStream。这是有道理的,因为通常你想阅读传入的请求,并相应地写一个回复。

于 2012-04-17T15:36:48.993 回答