我正在学习 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);
}
}
}