下载中文:
代码:
String str="船只博客";
OutputStream os=response.getOutputStream();
byte []byt=str.getBytes();
os.write(byt);html
用字节流输出,本地默认的是gbk的默认码表,用浏览器访问时也是本地默认的gbk码表,因此没有出现乱码。浏览器
在服务端用utf-8的码表:
byte []byt=str.getBytes(“UTF-8”);缓存
这时须要告知客户端用utf-8的码表解析:
方式一:
response.setHeader("ContexType","text/html;charset=UTF-8");
方式二:(推荐)
response.setContentType("text/html;charset=UTF-8");tomcat
更改服务器输出时使用的码表:
response.setCharacterEncoding("UTF-8");
使用方法二告知客户端使用指定的码表解码时,一样有告知服务器的功能,不须要告知服务器。服务器
下载文件中的图片
//得到文件的真实路径
ServletContext sc=getServletContext();
String str=sc.getRealPath("/WEB-INF/classes/text.jpg");
String filename=str.substring(str.lastIndexOf("//")+1);
//建立输入流
InputStream in=new FileInputStream(str);
//告知客户端如下载的形式打开
response.setHeader("Content-Disposition", "attachment;filename="+filename);
//建立字节输出流
OutputStream out=response.getOutputStream();
//输出
int len=-1;
byte []byt=new byte[1024];
while((len=in.read(byt))!=-1){
out.write(byt,0,len);
}
in.close();
out.close();编码
URL编码:
public static void encoding() throws UnsupportedEncodingException{
String str="戴佳伟";
System.out.println(URLEncoder.encode(str, "UTF-8"));
}code
URL解码:
private static void decoding() throws UnsupportedEncodingException {
// TODO Auto-generated method stub
String str="%E6%88%B4%E4%BD%B3%E4%BC%9F";
System.out.println(URLDecoder.decode(str, "UTF-8"));
}htm
定时刷新:
刷新类代码:图片
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Refresh", "2;URL=/TextResponse/2l.html");
response.getWriter().write("登陆成功,2秒后跳转到主页");utf-8
设置缓存时间:
response.setDateHeader("Expires", System.currentTimeMillis()+1*60*60);
缓存时间单位是毫秒,是个相对时间,须要获取当地时间。
response细节:OutputStream字节流和PrintWriter不能一块儿使用,是互斥的。OutputStream字节流和PrintWriter没必要关闭,tomcat会自动关闭。