HttpServletResponse
String data="中国77";
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.getOutputStream().write(data.getBytes("UTF-8"));
输出流的字符集应该与消息头设置的一致,使浏览器能够根据服务器返回的字符集在本地使用对应的字符集进行对数据解析。利用html中的meta标签模拟响应头
response.getOutputStream().write("<meta http-equiv='content-type,content='charset;UTF-8'>".getBytes());和response.setHeader("Content-type", "text/html;charset=UTF-8");的作用是一样的
当向流中写入数字时要将数字转换成字符输出,否则在流的另一端读取时会将数字作为ansi码对应的字符输出,例如
FileOutputStream out=new FileOutputStream("d:\\1.txt");
out.write(65);
在d:\1.txt中显示的内容为A
当我们向流中写入数据时,首先将数据写到了response对象中,并以某种编码存储
PrintWriter pw=response.getWriter();
pw.write("中国");
将显示??原因在于,在response对象中默认的编码为iso8859,当系统找不动中国对应的编码时变存储成??因此浏览器中显示的也是??因此要用response.setCharacterEncoding(string str)方法指导response对象使用的编码,当我们设置了浏览器响应头的编码后,可以不再设置response对象中的编码。
String data="中国77";
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.getOutputStream().write(data.getBytes("UTF-8"));
输出流的字符集应该与消息头设置的一致,使浏览器能够根据服务器返回的字符集在本地使用对应的字符集进行对数据解析。利用html中的meta标签模拟响应头
response.getOutputStream().write("<meta http-equiv='content-type,content='charset;UTF-8'>".getBytes());和response.setHeader("Content-type", "text/html;charset=UTF-8");的作用是一样的
当向流中写入数字时要将数字转换成字符输出,否则在流的另一端读取时会将数字作为ansi码对应的字符输出,例如
FileOutputStream out=new FileOutputStream("d:\\1.txt");
out.write(65);
在d:\1.txt中显示的内容为A
当我们向流中写入数据时,首先将数据写到了response对象中,并以某种编码存储
PrintWriter pw=response.getWriter();
pw.write("中国");
将显示??原因在于,在response对象中默认的编码为iso8859,当系统找不动中国对应的编码时变存储成??因此浏览器中显示的也是??因此要用response.setCharacterEncoding(string str)方法指导response对象使用的编码,当我们设置了浏览器响应头的编码后,可以不再设置response对象中的编码。
HttpServletResponse对象实现文件下载
package ResponseTest;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = this.getServletContext().getRealPath("/dowload/中国.jpg");//文件名含有中文则要经过URLencoder转码
String fileName=path.substring(path.lastIndexOf("\\")+1);
response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));//声明文件为下载类型并进行文件名转码
OutputStream out = response.getOutputStream();
InputStream in=new FileInputStream(path);
byte [] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1){
out.write(buf,0,len);
}
in.close();
out.close();
}
}