Java Servlet getInputStream错误

时间:2012-04-17 15:33:02

标签: java servlets

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

  

对于HttpServletResponse类型,未定义方法getInputStream()

当我尝试使用

ServletInputStream sis =  response.getInputStream();

提供的解决方案之一是

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);

            }
    }
}

3 个答案:

答案 0 :(得分:2)

听取原始错误:

  

方法getInputStream()未定义类型HttpServletResponse

这告诉你这个问题。 HttpServletResponse没有getInputStream()方法 - 它有一个没有意义。

getInputStream()位于HttpServletRequest

对于自动修复建议,Eclipse可能有点像白痴。

答案 1 :(得分:2)

那是因为ServletResponse / HttpServletResponse没有getInputStream()。 您实际上可能希望使用getInputStream中的HttpServletRequest

request.getInputStream()

答案 2 :(得分:0)

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