⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jsp1.txt

📁 jsp页面从mysql读取图片(BLOB)
💻 TXT
字号:
1.处理读取图片请求的servlet
public class ReadeImgServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, java.io.IOException {

		res.setContentType("Image/jpg");
		OutputStream out = res.getOutputStream();//获得响应的输出流,并将数据写入到客户端

		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		String drivername = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/mysql?user=root&password=871224";
		String sql = "select * from imgtab ";

		try {
			Class.forName(drivername);
			con = DriverManager.getConnection(url);

			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			if (rs.next()) {
				java.io.InputStream in = rs.getBinaryStream(1);//此流是远程流长度是不可测的
				byte b[] = new byte[in.available()];
				while (true) {
					int readLength = in.read(b);
					if (readLength == -1) {
						break;
					}
					out.write(b, 0, b.length);//实现将数据写到客户端的jsp页面中
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
				}
				if (con != null) {
					con.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}
}
2.web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  	<servlet-name>readeImg</servlet-name>
  	<servlet-class>com.tarena.dao.entity.ReadeImgServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>readeImg</servlet-name>
  	<url-pattern>/readeImg.do</url-pattern>
  </servlet-mapping>

</web-app>
3.jsp页面中的<img>:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    This is my JSP page. <img border="0" src="<%=basePath%>readeImg.do"/>
   </body>
</html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -