一、解决中文乱码问题,解决中文乱码问题有三种方法:
1)通过设置响应的头来处理的
response.setHeader("Content-Type","text/.html;charset=UTF-8");
2)通过字节设置响应的头来处理的
response.getOutputStream().write("中国".getBytes("UTF-8"));
3)使用html语言里面的<meta>标签来控制浏览器行为
response.getOutputStream().write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes());
二、文件下载
下面是文件下载的代码:
package cn.csdn.web.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo01Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*文件下载
* 首先知道下载的资源*/
ServletContext context = this.getServletContext();
String path =context.getRealPath("/WEB-INF/classes/res/aa.jpg");
/*构造文件*/
File file= new File(path);
/*构造文件的输入流*/
InputStream is = new FileInputStream(file);
/*写:输出流
* 文件下载*/
response.setHeader("content-disposition", "attachment;filename=");
OutputStream os = response.getOutputStream();
byte buffer[] = new byte[1024];
int len = 0;
while((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
}
os.close();
is.close();
}
}
如果下载的是中文文件,就把上面代码中的
String path =context.getRealPath("/WEB-INF/classes/res/aa.jpg")
aa.jpg改为汉字
把response.setHeader("content-disposition", "attachment;filename=");
加上URLEncoder.encode(file.getName(), "UTF-8")
如:response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(file.getName(), "UTF-8"));