Search.jsp頁面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>產品檢索</h1>
<form action="show.jsp" method="post">
產品編號:<input type="text" name = "id"></input>
<input type="submit" value="檢索">
</form>
</body>
</html>
Show.jsp頁面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<table border="1">
<tr><td>產品編號</td><td><%=request.getParameter("id") %></td></tr>
<tr><td>產品圖片</td><td><img src="showPhoto.do?id=<%=request.getParameter("id")%>"></img></td></tr>
</table>
</body>
</html>
Web.xml配置servlet
<servlet>
<description></description>
<display-name>ProductPhotoShowAction</display-name>
<servlet-name>ProductPhotoShowAction</servlet-name>
<servlet-class>com.city.oa.action.ProductPhotoShowAction</servlet-class>
<init-param>
<description></description>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<description></description>
<param-name>url</param-name>
<param-value>jdbc:odbc:DB</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ProductPhotoShowAction</servlet-name>
<url-pattern>/product/showPhoto.do</url-pattern>
</servlet-mapping>
ProductPhotoShowAction類中doPost()方法
String id = request.getParameter("id");
String sql = "select ProductNO,Photo,PhotoType from Product where ProductNO = ?"; //photo爲二進制數據,phototype爲圖片類型
String photoType = "";
String photo = "";
try {
if(!id.trim().equals("")){
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, Integer.parseInt(id));
ResultSet rs = ps.executeQuery();
InputStream in = null;
ServletOutputStream out = null;
if(rs.next()){
photoType = rs.getString("PhotoType");
response.setContentType(photoType);
response.setCharacterEncoding("utf-8");
in = rs.getBinaryStream("Photo");
out = response.getOutputStream();
byte[] data = new byte[200];
int len = 0;
while((len = in.read(data))!=-1){
out.write(data,0,len);
}
}
in.close();
out.flush();
out.close();
}else
response.sendRedirect("search.jsp");
} catch (Exception e) {
// TODO: handle exception
}
ProductPhotoShowAction類中init()方法
driver = this.getInitParameter("driver");
url = this.getInitParameter("url");
try {
Class.forName(driver);
con = DriverManager.getConnection(url);
} catch (Exception e) {
// TODO: handle exception
}
ProductPhotoShowAction類中destroy()方法
try {
if(con!=null&&!con.isClosed())
con.close();
} catch (Exception e) {
// TODO: handle exception
}