如何在<img/> src属性中提供servlet?

时间:2016-02-23 09:42:54

标签: java servlets

我使用以下代码在servlet中设置image标签中的src属性。但是它没有用,任何人都可以帮我这样做。

<img src="./imageDisplayProcess.do" alt="hai" width="117" height="160"/>

的Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        try{

                Class.forName("com.mysql.jdbc.Driver");
                Connection connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
                Statement st1=connection.createStatement();
                ResultSet rs1 = st1.executeQuery("select Qimg from tbl_MatchImgToImg where C_code='R201AEV01'");
                String imgLen="";
                if(rs1.next()){
                    imgLen = rs1.getString(1);
                    System.out.println(imgLen.length());
                }   
                rs1 = st1.executeQuery("select Qimg from tbl_MatchImgToImg where C_code='R201AEV01'");
                if(rs1.next()){
                    int len = imgLen.length();
                    byte [] rb = new byte[len];
                    java.io.InputStream readImg = rs1.getBinaryStream(1);
                    int index=readImg.read(rb, 0, len); 
                    System.out.println("index"+index);
                    st1.close();
                    response.reset();
                    response.setContentType("image/jpg");
                    response.getOutputStream().write(rb,0,len);
                    response.getOutputStream().flush();             
                }



    }
        catch(Exception e){
            System.out.println(e);
        }
        }

的web.xml

<servlet>
    <servlet-name>imageDisplayProcess</servlet-name>
    <servlet-class>get.imageDisplayProcess</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>imageDisplayProcess</servlet-name>
    <url-pattern>/imageDisplayProcess.do</url-pattern>
  </servlet-mapping>

1 个答案:

答案 0 :(得分:2)

假设您的servlet绑定到imageDisplayProcess.do:

使用HTTP GET请求获取使用HTML中的-Elements引用的图像。您在servlet中实现的是POST请求。

对于GET请求,您使用doGet()方法而不是doPost()。