赞
踩
得到web目录下的某个图片资源在浏览器上显示出来
package com.itheima.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @WebServlet(name = "Demo2Servlet", urlPatterns = "/demo2") public class Demo2Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 得到上下文对象 ServletContext application = getServletContext(); //2. 通过上下文对象的方法读取web/WEB-INF/图片文件,转成一个输入流 InputStream in = application.getResourceAsStream("/WEB-INF/cart504.jpg"); //3. 得到响应的字节输出流response.getOutputStream() OutputStream out = response.getOutputStream(); //4. 将输入流中数据复制到输出流中 int len = 0; byte[] buf = new byte[1024]; while((len=in.read(buf))!=-1) { out.write(buf,0,len); } //5. 关闭流 in.close(); out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
package com.itheima.servlet; import org.apache.commons.io.IOUtils; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @WebServlet(name = "Demo2Servlet", urlPatterns = "/demo2") public class Demo2Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 得到上下文对象 ServletContext application = getServletContext(); //2. 通过上下文对象的方法读取web/WEB-INF/图片文件,转成一个输入流 InputStream in = application.getResourceAsStream(</
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。