以HTML格式显示已从数据库中检索的图像

时间:2018-01-11 22:46:33

标签: java html json

我正在尝试使用java从数据库中读取HTML中的图像。我已经尝试了几种方式,我留下了评论,所以你可以看到我尝试过的。我读过很多类似的问题;然而,似乎没有人完全按照我的意思行事。我当前代码的结果是不显示图像。

我的代码是:

服务器端JAVA从数据库中提取图像:

public static Captcha randomCaptcha() {
    //Get connection
    MySQLConnection.getConnection();

    Captcha captcha = null; // necessary unless you do something in the exception handler
    String imageString = null;
    PreparedStatement ps = null;
    // Create connection/statement variables outside of try block
    Connection c = null;

    String selectQry = ("SELECT captcha_id, captcha_code " +
              "FROM at_captcha " +
              "ORDER BY RAND() LIMIT 0,1;");

    try {
        // Get Connection and Statement from DataSource
        c = ds.getConnection();
        ps = c.prepareStatement(selectQry);

        try {

            // Get result set
            ResultSet result = ps.executeQuery();

            while (result.next()) {
                imageString = getCaptchaImageData(result.getString("captcha_id"));
                captcha = new Captcha(
                        result.getString("captcha_id"),
                        imageString, 
                        result.getString("captcha_code"));
            }

            // Clean up
            ps.close();
            c.close();

        } catch (SQLException se) {
            System.out.println("SQLException in randomCaptcha: " + se.toString());
        } catch (Exception e) {
            System.out.println("Errors occurred in randomCaptcha: " + e.toString());
        }

    } catch (SQLException e1) {
        System.out.println("SQLException in randomCaptcha: " + e1.toString());
        e1.printStackTrace();

    } finally {

        // Ensure connection is closed and returned to the pool, even if errors occur.
        try {
            if(ps != null) ps.close();
            if(c != null) c.close();
        } 
        catch (Exception e) {
            System.out.println("Exception in randomCaptcha: " + e.toString());
        }
    }
    // Done
    return captcha;
}

public static String getCaptchaImageData(String id){
    //Get connection
    MySQLConnection.getConnection();

    PreparedStatement ps = null;
    String imageDataString = null;
    // Create connection/statement variables outside of try block
    Connection c = null;

    String selectQry = ("SELECT captcha_image " +
              "FROM at_captcha " + 
              "WHERE captcha_id = ?;");

    try {
        // Get Connection and Statement from DataSource
        c = ds.getConnection();
        ps = c.prepareStatement(selectQry);

        try {
            // Read in the image from the database.

            ps.setString(1, id);

            // Get result set
            ResultSet result = ps.executeQuery();

            while (result.next()) {
                java.sql.Blob imageBlob = result.getBlob(1);
                byte[] imageData = imageBlob.getBytes(1, (int) imageBlob.length());

                //Convert Image byte array into Base64 String
                imageDataString = encodeImage(imageData);
                imageDataString = "data:image/jpeg;base64,"+imageDataString;
            }

            // Clean up
            ps.close();
            c.close();

        } catch (SQLException se) {
            System.out.println("SQLException in getCaptchaImageData: " + se.toString());
        } catch (Exception e) {
            System.out.println("Errors occurred in getCaptchaImageData: " + e.toString());
        }

    } catch (SQLException e1) {
        System.out.println("SQLException in getCaptchaImageData: " + e1.toString());
        e1.printStackTrace();

    } finally {

        // Ensure connection is closed and returned to the pool, even if errors occur.
        try {
            if(ps != null) ps.close();
            if(c != null) c.close();
        } 
        catch (Exception e) {
            System.out.println("Exception in getCaptchaImageData: " + e.toString());
        }
    }
    // Done
    return imageDataString;
}

客户端JAVA调用服务器端然后传回图像:

@WebServlet("/CaptchaView")
public class CaptchaView extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // Find a random Captcha   
    Captcha aCaptcha = MySQLConnection.randomCaptcha();

    //Store the selected Captcha ID for later use
    MySQLConnection.setViewDataCaptchaID(aCaptcha.getCaptchaId());

    String json = new Gson().toJson(aCaptcha.getCaptchaImage());
    //response.setContentType("application/json");
    response.resetBuffer();
    response.setContentType("image/jpeg");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}
}

我的JSON调用java然后将图像嵌入到html:

$('#selectState').on('change', function() {
    $.ajax({
        type: "POST",
        url: "CaptchaView",
        cache: false,
        data: $(selectState).serialize(),
        success: function(data1a){
            $('#ajaxGetUserServletResponse').text(data1a);
        }
    }).done(function(responseJson1a) {
        var byte[] img = Base64.decode(responseJson1a, Base64.DEFAULT);
//      var img = new Image(esponseJson1a);
        dataType: "json",
        //$("#captureDisplay").find("image").remove();
        // JSON response to populate the image

//      $("#img-container").img.src = img;
//      $("#img-container").img.setAttribute("class", "banner-img");
//      $("#img-container").img.setAttribute("alt", "effy");
//      $("#img-container").document.getElementById("img-container").appendChild(img);

        $('<img src').object(img).appendTo($("#img-container"));

    });
});

我的HTML这是我想要显示图片的地方:

<div class="input-group" id="img-container">
</div>

1 个答案:

答案 0 :(得分:0)

详细说明:

随机获取Captcha:

        public static Captcha randomCaptcha() {
        //Get connection
        MySQLConnection.getConnection();

        Captcha captcha = null; // necessary unless you do something in the exception handler
        String imageString = null;
        PreparedStatement ps = null;
        // Create connection/statement variables outside of try block
        Connection c = null;

        String selectQry = ("SELECT captcha_id, captcha_code " +
                  "FROM at_captcha " +
                  "ORDER BY RAND() LIMIT 0,1;");

        try {
            // Get Connection and Statement from DataSource
            c = ds.getConnection();
            ps = c.prepareStatement(selectQry);

            try {

                // Get result set
                ResultSet result = ps.executeQuery();

                while (result.next()) {
                    imageString = getCaptchaImageData(result.getString("captcha_id"));
                    captcha = new Captcha(
                            result.getString("captcha_id"),
                            imageString, 
                            result.getString("captcha_code"));
                }

                // Clean up
                ps.close();
                c.close();

            } catch (SQLException se) {
                System.out.println("SQLException in randomCaptcha: " + se.toString());
            } catch (Exception e) {
                System.out.println("Errors occurred in randomCaptcha: " + e.toString());
            }

        } catch (SQLException e1) {
            System.out.println("SQLException in randomCaptcha: " + e1.toString());
            e1.printStackTrace();

        } finally {

            // Ensure connection is closed and returned to the pool, even if errors occur.
            // This is *very* important if using a connection pool, because after all the
            // connections are used, the application will hang on getConnection(), waiting
            // for a connection to become available.
            // Any errors from the following closes are just ignored.  The main thing is
            // that we have definitely closed the connection.
            try {
                if(ps != null) ps.close();
                if(c != null) c.close();
            } 
            catch (Exception e) {
                System.out.println("Exception in randomCaptcha: " + e.toString());
            }
        }
        // Done
        return captcha;
    }

        public static String getCaptchaName(String captchaID) {
        //Get connection
        MySQLConnection.getConnection();

        String captchaName = null; // necessary unless you do something in the exception handler
        PreparedStatement ps = null;
        // Create connection/statement variables outside of try block
        Connection c = null;

        String selectQry = ("SELECT captcha_code " +
                  "FROM at_captcha " +
                  "WHERE captcha_id = ?");

        try {
            // Get Connection and Statement from DataSource
            c = ds.getConnection();
            ps = c.prepareStatement(selectQry);

            try {
                ps.setString(1, captchaID);

                // Get result set
                ResultSet result = ps.executeQuery();

                while (result.next()) {
                    captchaName = result.getString("captcha_code");
                  }

                // Clean up
                ps.close();
                c.close();

            } catch (SQLException se) {
                System.out.println("SQLException in getCaptchaName: " + se.toString());
            } catch (Exception e) {
                System.out.println("Errors occurred in getCaptchaName: " + e.toString());
            }

        } catch (SQLException e1) {
            System.out.println("SQLException in getCaptchaName: " + e1.toString());
            e1.printStackTrace();

        } finally {

            // Ensure connection is closed and returned to the pool, even if errors occur.
            // This is *very* important if using a connection pool, because after all the
            // connections are used, the application will hang on getConnection(), waiting
            // for a connection to become available.
            // Any errors from the following closes are just ignored.  The main thing is
            // that we have definitely closed the connection.
            try {
                if(ps != null) ps.close();
                if(c != null) c.close();
            } 
            catch (Exception e) {
                System.out.println("Exception in getCaptchaName: " + e.toString());
            }
        }
        // Done
        return captchaName;
    }

爪哇:

@WebServlet("/CaptchaView")
public class CaptchaView extends HttpServlet implements Serializable {

    private static final long serialVersionUID = 1L;

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Find a random Captcha   
        Captcha aCaptcha = MySQLConnection.randomCaptcha();

        //Store the selected Captcha ID for later use
        MySQLConnection.setViewDataCaptchaID(aCaptcha.getCaptchaId());

        String json = aCaptcha.getCaptchaImage();
        json = "<img src=" + json + " width='250' alt='captcha image' >";
        //response.setContentType("application/json");
        response.resetBuffer();
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
}

的Ajax:

$.ajax({
        type: "POST",
        url: "CaptchaView",
        cache: false,
        success: function(data1a){
            //$('#ajaxGetUserServletResponse').text(data1a);
        },
        error: function() {
            $("#selectState").focus();
            $('#ajaxGetUserServletResponse').text('An error occured getting the Captcha image');
        }
    }).done(function(responseJson1a) {
        //alert($(responseJson1a).val());
        //alert($(responseJson1a));
        dataType: "json";
        $("#img-container").find("img").remove();
        // JSON response to populate the image
        $(responseJson1a).appendTo($("#img-container"));

    });

HTML:

<!-- Place for Captcha image -->
<div class="input-group" id="img-container">
</div>
相关问题