将MySQL数据库中的1个列表图像加载到列表JSP页面中

时间:2017-04-12 11:44:46

标签: java jquery html mysql jsp

我的jsp页面有问题。 首先我创建一个数据库有表图像有一些属性imageID,imageTitle,imageURL,imageStyle 继续我创建一个新的jsp页面 这是代码:

<%@page import="java.sql.*"%>
<%@page import="com.mysql.jdbc.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
            try {
            String _URL = "jdbc:mysql://localhost/slider";
            String _USER = "root";
            String _PASS = "password";
            java.sql.Connection connection = null;

            Class.forName("com.mysql.jdbc.Driver").newInstance(); 
            connection = DriverManager.getConnection(_URL, _USER, _PASS);
            //if(!connection.isClosed())
                 //out.println("Successfully connected to " + "MySQL server using TCP/IP...");
            //connection.close();

            int img_id = 1;
            ResultSet rs = null;
            PreparedStatement pstmt = null;
            String strslide = "";
            strslide += "<div class=\"panel\">";

            strslide += "<div class=\"container\"><div class=\"wt-rotator\">";
            strslide +="<a href=\"#\"></a>";
            strslide += "<div class=\"desc\"></div><div class=\"preloader\"></div><div class=\"c-panel\"><div class=\"buttons\">";
            strslide+="<div class=\"prev-btn\"></div>";
            strslide+="<div class=\"play-btn\"></div>";
            strslide+="<div class=\"next-btn\"></div>";

            strslide+="</div>";

            strslide +="<div class=\"thumbnails\">";
            strslide += "<ul>"; 
            try {
                pstmt = connection.prepareStatement("select * from image where id = @id");
                pstmt.setInt(1, img_id);
                rs = pstmt.executeQuery();
                if(rs.next()) {
                   // some code at here
                }
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }catch(Exception ex){
            out.println("Unable to connect to database"+ex);
        } 

        %>
    </body>
</html>

我不知道如何用jsp代码将图像显示到页面中,这段代码我写了一些理想的代码。我创建了连接到mysql,之后我选择查询从表图像中获取一些属性。之后我想在我的代码中添加propeerties以将图像显示到页面中。

在这里我有一个css文件,一个js文件,一些路径图片/ ...

的图片

谢谢!

1 个答案:

答案 0 :(得分:0)

首先在jsp中执行java代码是不好的做法。你必须创建单独的类SliderDao并将所有jdbc代码放在那里。

创建PreparedStatement不像:

pstmt = connection.prepareStatement("select * from image where id = @id");

应该是

pstmt = connection.prepareStatement("select * from image where id = ?");
pstmt.setInt(1, img_id);
rs = pstmt.executeQuery();

阅读本教程http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html#create_ps