servlet笔记
http响应头包括:
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../.
Refresh:告诉客户端,多久刷新一次;
Location:让网页重新定位;
ServletContext很重要:容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用
读取配置文件并显示用户名和密码:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); InputStream inputStream = context.getResourceAsStream("/WEB-INF/classes/db.properties"); //web-inf前面的 / 一定要写,那个代表当前web项目 Properties properties = new Properties(); properties.load(inputStream); String name = properties.getProperty("username"); String pw = properties.getProperty("password"); resp.getWriter().print(name+pw); }
下载文件:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1. 要获取下载文件的路径 String realPath = "F:\job\demo\javaweb\servlet-01\src\main\resource\2.png"; System.out.println("下载文件的路径:"+realPath); // 2. 下载的文件名是啥? String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); // 3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码 resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8")); // 4. 获取下载文件的输入流 FileInputStream in = new FileInputStream(realPath); // 5. 创建缓冲区 int len = 0; byte[] buffer = new byte[1024]; // 6. 获取OutputStream对象 ServletOutputStream out = resp.getOutputStream(); // 7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端! while ((len=in.read(buffer))>0){ out.write(buffer,0,len); } in.close(); out.close(); }
这两段代码用了不同的输出方式。
PrintWriter getWriter() throws IOException; ServletOutputStream getOutputStream() throws IOException;
response.getOutputStream()向浏览器输出的是二进制数据,是字节流,可以处理任意类型的数据,而response.getWriter()输出的是字符型数据,是字符流。
所以输出文本getOutputStream()和response.getWriter()都可以用,下载文件只能用response.getOutputStream()
使用getOutputStream()时要设置响应头,告诉浏览器你要干什么
浙公网安备 33010602011771号