1.创建一个maven的web项目,加入oracle10/postgresql9.4驱动包依赖(本项目使用两种数据源进行测试)
依赖如下
<!-- Oracle驱动包 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.2.0</version>
</dependency>
<!-- Postgresql驱动包 -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1206-jdbc41</version>
</dependency>
2.创建jdbc获取数据库连接的工具类(未使用连接池,仅供测试)
oracle版
public class OracleConnTool{
private static String url = "jdbc:oracle:thin:@数据库ip地址:1521:ORCL";
private static String user = "你的数据库用户名";
private static String pwd = "你的数据库密码";
public static Connection getConnection(){
Connection conn = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url,user,pwd);
if(null != conn){
System.out.println("数据库连接成功。con是:" + conn);
}else{
Systme.out.println("连接失败!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Postgresql版
public class PostgresqlConnTool{
private static String url = "jdbc:postgresql://172.10.103.77:5432/cs_tyrz?searchpath=public";
private static String user = "cs_tyrz";
private static String pwd = "cs_tyrz";
public static Connection getConnection(){
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url,user,pwd);
if(null != conn){
System.out.println("数据库连接成功。con是:" + conn);
}else{
Systme.out.println("连接失败!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
3.创建一个Servlet测试使用
仅贴出doGet方法了
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
String sql = "select * from DATA_11";
Statement pstmt = null;
Connection conn = PostgresqlConnTool.getConnection();
try{
pstmt = conn.createStatement();
ResultSet rs = pstmt.executeQuery(sql);
rs.next();//只读一条测试数据出来。
InputStream is = rs.getBinaryStream("xp");
System.out.println(is.toString());
resp.setContentType("image/*");
ServletOutputStream os = resp.getOutputStream();
//注意这里BASE64Decoder需要设置一下build path,CSDN博客里的教程 http://blog.csdn.net/weixin_35852328/article/details/78557275
byte[] deis = new sun.misc.BASE64Decoder().decodeBuffer(is);
os.write(deis);
os.close();
is.close();
rs.close();
}catch (Exception e){
e.printStackTrace();
}finally{
try{
pstmt.close();
}catch(Excetion e){
e.printStackTrace();
}
}
}
4.jsp页面
<img src="你写的servlet名称">
5.没有意外的话就可以显示你存在数据库的 Base64编码后的图片数据了。