使用response将图片展示在浏览器页面中

import javax.servlet.ServletOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImgServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    doPost(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        InputStream in =new FileInputStream("E:\\IMg\\图片\\Saved Pictures\\12.29.5.jpg");//图片地址
        ServletOutputStream o=response.getOutputStream();//获取servlet输出流

        byte[] bytes = new byte[1024];//设置字节
        int len=0;
        while ((len=in.read(bytes))!=-1){
            o.write(bytes,0,len);//打印在页面上
        }
        //关闭资源
        in.close();
        o.close();
    }
}

需要设置一下默认跳转地址,要不然会默认运行index,不设置的话需要在运行之后在地址栏里边的地址后边输入xml里边中所写的地址


        ImgServlet
        /img
    
    
        img//设置默认运行(与上方所写地址:img相对应)
    

你可能感兴趣的:(jsp)