编了一个Servlet,出现java.lang.IllegalStateException: getWriter() has already been called for this
packagecom.lai;importjava.io.*;importjavax.servlet.ServletException;importjavax.servl...
package com.lai;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//演示下载文件
response.setHeader("Content-Disposition", "attachment;filename=girl.jpg");
//打开文件。说明一下web站点下载文件的原理
//1.获取到要下载文件的全路径
String path=this.getServletContext().getRealPath("/image/girl.jpg");
//System.out.println("path="+path);
//2.创建一个文件输入流
FileInputStream fis=new FileInputStream(path);
//做一个缓冲字节数组
byte buff[]=new byte[1024];
int len=0;//表示实际每次读取了多少个字节
OutputStream os=response.getOutputStream();
while((len=fis.read(buff))>0){
os.write(buff, 0, len);
}
//关闭
os.close();
fis.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
刷新页面的时候就出错,好像是服务器出错了吗? 展开
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//演示下载文件
response.setHeader("Content-Disposition", "attachment;filename=girl.jpg");
//打开文件。说明一下web站点下载文件的原理
//1.获取到要下载文件的全路径
String path=this.getServletContext().getRealPath("/image/girl.jpg");
//System.out.println("path="+path);
//2.创建一个文件输入流
FileInputStream fis=new FileInputStream(path);
//做一个缓冲字节数组
byte buff[]=new byte[1024];
int len=0;//表示实际每次读取了多少个字节
OutputStream os=response.getOutputStream();
while((len=fis.read(buff))>0){
os.write(buff, 0, len);
}
//关闭
os.close();
fis.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
刷新页面的时候就出错,好像是服务器出错了吗? 展开
3个回答
展开全部
getWriter() 和getOutputStream() 只能用一个,一个字符输出流,一个字节输出流,都获取后就会出现这个异常。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
去掉 PrintWriter out = response.getWriter();
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询