jsp與數據庫的面對面交流html
前言:要完成數據的交互的一種方式就是jsp+jsp+數據庫。下面就來演示一個用jsp展現數據庫內的圖片的小例子。java
準備工做:mysql
在數據庫中新建一張存放圖片的表。
新建兩張jsp頁面,分別是MyJsp1.jsp (處理鏈接) 和 MyJsp2.jsp (展現圖片)。
實施:sql
建表數據庫
create table img (
id int auto_increment primary key,
name varchar(100) ,
image blob //blob是數據庫中存放圖片的類型
)
MyJsp1.jsp數組
<%@ page contentType="text/html; charset=gbk" %>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.math.*"%>
<%String id = request.getParameter("id"); // 接收參數oracle
//mysql鏈接
Class.forName("com.mysql.jdbc.Driver").newInstance();
String URL="jdbc:mysql://localhost:3306/img?user=root&password=123";
Connection con = DriverManager.getConnection(URL);
System.out.println(con); //測試鏈接數據庫是否成功jsp
//oracle鏈接
//String URL="jdbc:oracle:thin@localhost:1521:orcl2";
//user="system";
//password="manager";
//Connection con = DriverManager.getConnection(URL,user,password);
try{測試
// 準備語句執行對象
Statement stmt = con.createStatement();
String sql = " SELECT * FROM img WHERE id = "+ id;
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
Blob b = rs.getBlob("image"); //獲取表的image字段,即圖片的二進制
long size = b.length(); //計算圖片長度
byte[] bs = b.getBytes(1, (int)size); //放入數組
response.setContentType("image/jpg"); //設置給響應的頁面一個的響應的內容格式爲圖片
OutputStream outs = response.getOutputStream(); // 使用輸出流
outs.write(bs); //將數組寫入輸出流
outs.flush(); //刷新輸出流
rs.close(); //關閉結果集
}
else {
rs.close();
}
}
finally{
con.close(); //關閉鏈接
out.clear();
out = pageContext.pushBody();
}
%>code
MyJsp2.jsp
<body>
<img src="MyJsp1.jsp?id=1">
</body>