struts2响应文件 struts2下载txt

public class txtAction extends ActionSupport {

private String type;

@Action(value="getTxt")
public String getTxt() {
if("txt".equals(type)){
String restxt="鲲鹏展翅";

ServletActionContext.getResponse().setContentType("text/plain");

ServletActionContext.getResponse().setCharacterEncoding("gbk");
ServletActionContext.getResponse().setHeader("connection", "close");
ServletActionContext.getResponse().setHeader("Content-Disposition","attachement;filename="+System.currentTimeMillis()+".txt");

try {
InputStream is = new ByteArrayInputStream(restxt.getBytes("UTF-8"));

//通过response获得输出流
OutputStream os=ServletActionContext.getResponse().getOutputStream();
byte[] b=new byte[1024];
int len=0;
while((len=is.read(b))!=-1){
os.write(b, 0, len);
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}


public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}

}

原文地址:https://www.cnblogs.com/zjk1/p/9253599.html