如何在servlet的json响应中发送带有一些数据的图像

时间:2018-12-12 12:44:46

标签: java mysql json jsp servlets

我想从servlet发送json。该servlet从mysql数据库获取数据和多个图像。现在我想将此数据放入json并将其发送给用户。但是当我运行此SendJsonData.java时给出这样的输出..如何获取图像..

其中mysql用户表具有col--name,city,image1.image2 ....

[{"name":"rohit","city":"mumbai","image1":""com.mysql.jdbc.Blob@1b6d1381","image2":""com.mysql.jdbc.Blob@1b6d45881"}{...}{..}]

servlet:SendJsondata.java

package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

public class SendJsonData extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        PrintWriter out=response.getWriter();
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");

        Connection conn=null;
        String dbPath = "";
        String username = "";
        String password = "";

        try{
            String name=null;
            String city=null;
            Blob image1;
            Blob image2

            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(dbPath, username, password);

           Statement st = conn.createStatement();
           ResultSet rs = st.executeQuery("select name,city,image1,image2 from user LIMIT 10");
           JSONArray jArray = new JSONArray();
           JSONObject json=new JSONObject();
           while(rs.next()){

                name=rs.getString("name");
                city=rs.getString("city");
                image1=rs.getBlob("image1");
                image2=rs.getBlob("image2");

                json.put("name", name);
                json.put("city", city);
                json.put("image1", image1);
                json.put("image2", image2);

                jArray.put(json);

           }
       out.println(jArray);
            conn.close();                            
        }

        catch(Exception e){            
            out.print(e);            
        }            
    }    
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

0 个答案:

没有答案