- 1@webServlet("/ResponseDemo2") 2 public class ResponseDemo2 extends HttpServlet {
- 3
- /**
- 4 * 案例-Content-Type的作用
- 5 */
- 6 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
- IOException {
- 7
- /**
- 8 * 设置响应实体内容编码
- 9 */
- 10 //response.setCharacterEncoding("utf-8");
- 11 12
- /**
- 13 * 1.服务器发给浏览器的数据类型
- 14 */
- 15 //response.setHeader("content-type", "text/html");
- 16 17 //response.setContentType("text/html");//和上面代码等价,加以使用此方法
- 18 //上面的两行代码可以合并成一行代码
- 19 response.setContentType("text/html;charset=utf-8");
- 20 21 //response.setContentType("image/png");//发送图片
- 22 23 response.getWriter().write("this is a title中国");
- 24 response.getOutputStream().write("this is a title中国".getBytes("utf-8"));
- 25
- /*如果html文件中有中文,则会出现乱码,方法中涉及到转码问题,一般都默认iso-8859-1*/
- 26
- /*所以response.getWriter()之前使用response.setCharacterEncoding("utf-8");设置相应内容编码*/
- 27 28 29
- /* File file=new File("C:/Users/MaoDoer/Desktop/pic.png");
- 30 */
- /**
- 31 * 设置以下载的方式打开文件
- 32 */
- /*
- 33 response.setHeader("content-disposition","attachment;filename="+file.getName());
- 34 */
- /**
- 35 * 下载图片
- 36 */
- /*
- 37 */
- /**
- 38 * 发送图片
- 39 */
- /*
- 40 FileInputStream in = new FileInputStream(file);
- 41 byte[] buf=new byte[1024];
- 42 int len=0;
- 43 while((len=in.read(buf))!=-1){
- 44 response.getOutputStream().write(buf, 0, len);
- 45 }
- 46 */
- 47
- }
- 48
- }
来源: http://www.bubuko.com/infodetail-1950615.html