编了一个Servlet,出现java.lang.IllegalStateException: getWriter() has already been called for this

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

}
刷新页面的时候就出错,好像是服务器出错了吗?

把PrintWriter out = response.getWriter();删掉,因为你已经有一个OutputStream的。。建议你下次把那些get和post方法里面的代码都删掉再写你自己想写的代码。那样就不会影响进行别的操作!希望可以帮到你。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-07-23
getWriter() 和getOutputStream() 只能用一个,一个字符输出流,一个字节输出流,都获取后就会出现这个异常。
第2个回答  2013-07-22
去掉 PrintWriter out = response.getWriter();

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网