- 浏览: 21409 次
- 性别:
- 来自: 北京
文章分类
最新评论
在实际的开发中,我们可能需要将图片、影音等文件直接保存到数据库中,然后通过编程方式将数据读出进行使用。例如将读出的图片数据显示出来,将读出的电影文件播放出来。
二进制数据直接保存到文件和从文件中读出非常的简单。和普通的数据库操作差别不大。只是用到部分流操作。例如各种输入输出流操作。所以深刻理解流操是非常重要的。
在此我借助于一个JSP的简单实例进行讲解。此实例保存职员数据,其中职员数据包含一个图片列。此列保存每名员工的照片。在此将照片直接保存到数据库中。首先建立职员信息表EmployeeInfo,表列非常的简单
employeeId:职员编号(自动增长);employeeName:职员姓名;age:职员年龄;pic:职员图片(image类型)
首先讲解信息的保存。先建立一个录入界面index.jsp,其中包含一个<input type="file"/>元素,用于让用户选择图片文件。
页面代码如下(不做过多讲解):
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>
<form action="addServlet" method="POST">
<table border="15" width="60%" align="center">
<tr>
<td width="30%" align="right">EmployeeName:</td>
<td width="70%" align="left"><input type="text" name="employeeName"/></td>
</tr>
<tr>
<td width="30%" align="right">Age:</td>
<td width="70%" align="left"><input type="text" name="age"/></td>
</tr>
<tr>
<td width="30%" align="right">Image:</td>
<td width="70%" align="left"><input type="file" name="pic"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="add"/></td>
</tr>
</table>
</form>
</body>
</html>
页面请求addServlet,获取录入信息,并调用JavaBean实现数据保存。Servlet代码如下:
package com.frank.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.frank.rule.*;
public class AddServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public AddServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String employeeName=request.getParameter("employeeName");
int age=Integer.parseInt(request.getParameter("age"));
String pic=request.getParameter("pic");
EmployeeDAO employeeDAO=new EmployeeDAO();
if(employeeDAO.employeeAdd(employeeName, age, pic))
response.sendRedirect("success.jsp");
else
response.sendRedirect("index.jsp");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
此Servlet只是简单的获取页面输入的数据,其中获取的Pic为用户选择的图片路径。严格讲,获取文件需要经过验证,防止非法图片的选择,这个可以根据自己的需要改善。然后Servlet调用业务类,将获取的数据通过参数传入,进行数据的增加。其中employeeAdd方法实现数据的保存,代码如下:
public boolean employeeAdd(String employeeName,int age,String pic){
Connection conn=null;
PreparedStatement pstmt=null;
FileInputStream fis=null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
fis=new FileInputStream(pic);
String strSQL="INSERT INTO employeeInfo VALUES(?,?,?)";
pstmt=conn.prepareStatement(strSQL);
pstmt.setString(1, employeeName);
pstmt.setInt(2, age);
pstmt.setBinaryStream(3, fis, fis.available());
if(pstmt.executeUpdate()>0)
return true;
else
return false;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return false;
}catch(SQLException ex){
ex.printStackTrace();
return false;
}catch(IOException ex){
ex.printStackTrace();
return false;
}finally{
try{
fis.close();
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
注意粗体部分,用获取的pic信息(文件路径)创建文件输入流对象,增加pic字段的内容通过流对象增加。
pstmt.setBinaryStream(3, fis, fis.available());
三个参数分别为:参数索引,流对象,流对象大小
当增加成功时,重定向到success.jsp
运行结果如下:
增加后,显示如下代表成功:
那么如何验证图片数据是否保存到了数据库中呢?我们通过再次检索增加的数据,读出增加的图片数据并在页面中显示出来进行验证。
首先建立一个非常简单的页面search.jsp,此页面通过文本框使用户输入要检索的人员的姓名,检索人员的基本信息(不检索图片数据),将检索的人员数据形成JOPO对象,保存到session中,以便页面使用。
POJO类(EmployeeObj)
package com.frank.obj;
public class EmployeeObj {
private int employeeId;
private String employeeName;
private int age;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
search.jsp页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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 'search.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>
<form action="searchServlet" method="POST">
employeeName:<input type="text" name="employeeName"/>
<input type="submit" value="search"/>
</form>
</body>
</html>
通过searchServlet实现基本信息的检索
package com.frank.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.frank.obj.EmployeeObj;
import com.frank.rule.EmployeeDAO;
public class SearchServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public SearchServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String employeeName=request.getParameter("employeeName");
EmployeeDAO employeeDAO=new EmployeeDAO();
EmployeeObj employeeObj=employeeDAO.getEmployeeByName(employeeName);
HttpSession session=request.getSession();
session.setAttribute("employee", employeeObj);
response.sendRedirect("display.jsp");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
此Servlet调用业务类的getEmployeeByName方法检索人员基本信息,返回EmployeeObj对象,并放入session中,当然也可以放入request中,根据自己的需要改进。页面检索成功后重定向到display.jsp进行信息的显示(稍后讲解)
getEmployeeByName方法代码如下:
public EmployeeObj getEmployeeByName(String employeeName){
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
EmployeeObj employeeObj=new EmployeeObj();
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
String strSQL="SELECT employeeId,employeeName,age FROM EmployeeInfo WHERE employeeName=?";
pstmt=conn.prepareStatement(strSQL);
pstmt.setString(1, employeeName);
rst=pstmt.executeQuery();
if(rst.next()){
employeeObj.setEmployeeId(rst.getInt("employeeId"));
employeeObj.setEmployeeName(rst.getString("employeeName"));
employeeObj.setAge(rst.getInt("age"));
return employeeObj;
}
return null;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return null;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}finally{
try{
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
display.jsp负责显示查询出的结果信息,代码如下:
<%@ page language="java" import="java.util.*,com.frank.obj.*" pageEncoding="ISO-8859-1"%>
<%
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 'display.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">
-->
<%
EmployeeObj employeeObj=(EmployeeObj)session.getAttribute("employee");
%>
</head>
<body>
<table width="80" border="15">
<tr>
<td width="30%" align="right">EmployeeId</td>
<td width="70%" align="left"><%=employeeObj.getEmployeeId() %></td>
</tr>
<tr>
<td width="30%" align="right">EmployeeName</td>
<td width="70%" align="left"><%=employeeObj.getEmployeeName() %></td>
</tr>
<tr>
<td width="30%" align="right">Age</td>
<td width="70%" align="left"><%=employeeObj.getAge() %></td>
</tr>
<tr>
<td width="30%" align="right">Pic</td>
<td width="70%" align="left"><img src="displayServlet?employeeId=<%=employeeObj.getEmployeeId() %>"/></td>
</tr>
</table>
</body>
</html>
代码非常的简单,只是简单的从session中获取保存的EmployeeObj对象,然后利用jsp表达式将数据成员信息显示到页面上。但是注意粗体部分,因为我们需要将保存的图片数据读出,然后显示成图片。所以在此我们利用Img元素显示图片,而Src利用displayServlet的运行结果输出到客户端,作为图片的显示源。displayServlet包含参数employeeId,用来决定具体显示哪一员工的图片。
displayServlet通过Servlet输出流,将读取的图片数据发送到客户端,代码如下:
package com.frank.action;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.frank.rule.EmployeeDAO;
public class DisplayServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public DisplayServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/gif");
int employeeId=Integer.parseInt(request.getParameter("employeeId"));
EmployeeDAO employeeDAO=new EmployeeDAO();
InputStream is=employeeDAO.getPicById(employeeId);
int size=is.available();
byte[] image=new byte[size];
is.read(image);
ServletOutputStream out=response.getOutputStream();
out.write(image);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
在此,调用业务类的getPicById方法得到图片数据的输入流。然后获取的输入流写到ServletOutputStream,这样可以在Servlet的输出端使用,即img的src中使用
getPicById代码如下:
public InputStream getPicById(int employeeId){
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
InputStream is=null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
String strSQL="SELECT pic FROM EmployeeInfo WHERE employeeId=?";
pstmt=conn.prepareStatement(strSQL);
pstmt.setInt(1, employeeId);
rst=pstmt.executeQuery();
if(rst.next()){
is=rst.getBinaryStream("pic");
return is;
}
return null;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return null;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}finally{
try{
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
注意粗体部分
好了,我们可以通过运行结果来进行验证,假设我们搜索名称为Mike的人员数据,那么这样:
点search按钮,运行结果如下:
好了,显示出了检索结果,不但包括人员的基本数据,保存到数据库中的图片数据也被读出并显示成图片。
代码只是利用jsp简单的进行体现,大家可以根据自己的需要进行改进。
二进制数据直接保存到文件和从文件中读出非常的简单。和普通的数据库操作差别不大。只是用到部分流操作。例如各种输入输出流操作。所以深刻理解流操是非常重要的。
在此我借助于一个JSP的简单实例进行讲解。此实例保存职员数据,其中职员数据包含一个图片列。此列保存每名员工的照片。在此将照片直接保存到数据库中。首先建立职员信息表EmployeeInfo,表列非常的简单
employeeId:职员编号(自动增长);employeeName:职员姓名;age:职员年龄;pic:职员图片(image类型)
首先讲解信息的保存。先建立一个录入界面index.jsp,其中包含一个<input type="file"/>元素,用于让用户选择图片文件。
页面代码如下(不做过多讲解):
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>
<form action="addServlet" method="POST">
<table border="15" width="60%" align="center">
<tr>
<td width="30%" align="right">EmployeeName:</td>
<td width="70%" align="left"><input type="text" name="employeeName"/></td>
</tr>
<tr>
<td width="30%" align="right">Age:</td>
<td width="70%" align="left"><input type="text" name="age"/></td>
</tr>
<tr>
<td width="30%" align="right">Image:</td>
<td width="70%" align="left"><input type="file" name="pic"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="add"/></td>
</tr>
</table>
</form>
</body>
</html>
页面请求addServlet,获取录入信息,并调用JavaBean实现数据保存。Servlet代码如下:
package com.frank.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.frank.rule.*;
public class AddServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public AddServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String employeeName=request.getParameter("employeeName");
int age=Integer.parseInt(request.getParameter("age"));
String pic=request.getParameter("pic");
EmployeeDAO employeeDAO=new EmployeeDAO();
if(employeeDAO.employeeAdd(employeeName, age, pic))
response.sendRedirect("success.jsp");
else
response.sendRedirect("index.jsp");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
此Servlet只是简单的获取页面输入的数据,其中获取的Pic为用户选择的图片路径。严格讲,获取文件需要经过验证,防止非法图片的选择,这个可以根据自己的需要改善。然后Servlet调用业务类,将获取的数据通过参数传入,进行数据的增加。其中employeeAdd方法实现数据的保存,代码如下:
public boolean employeeAdd(String employeeName,int age,String pic){
Connection conn=null;
PreparedStatement pstmt=null;
FileInputStream fis=null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
fis=new FileInputStream(pic);
String strSQL="INSERT INTO employeeInfo VALUES(?,?,?)";
pstmt=conn.prepareStatement(strSQL);
pstmt.setString(1, employeeName);
pstmt.setInt(2, age);
pstmt.setBinaryStream(3, fis, fis.available());
if(pstmt.executeUpdate()>0)
return true;
else
return false;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return false;
}catch(SQLException ex){
ex.printStackTrace();
return false;
}catch(IOException ex){
ex.printStackTrace();
return false;
}finally{
try{
fis.close();
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
注意粗体部分,用获取的pic信息(文件路径)创建文件输入流对象,增加pic字段的内容通过流对象增加。
pstmt.setBinaryStream(3, fis, fis.available());
三个参数分别为:参数索引,流对象,流对象大小
当增加成功时,重定向到success.jsp
运行结果如下:
增加后,显示如下代表成功:
那么如何验证图片数据是否保存到了数据库中呢?我们通过再次检索增加的数据,读出增加的图片数据并在页面中显示出来进行验证。
首先建立一个非常简单的页面search.jsp,此页面通过文本框使用户输入要检索的人员的姓名,检索人员的基本信息(不检索图片数据),将检索的人员数据形成JOPO对象,保存到session中,以便页面使用。
POJO类(EmployeeObj)
package com.frank.obj;
public class EmployeeObj {
private int employeeId;
private String employeeName;
private int age;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
search.jsp页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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 'search.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>
<form action="searchServlet" method="POST">
employeeName:<input type="text" name="employeeName"/>
<input type="submit" value="search"/>
</form>
</body>
</html>
通过searchServlet实现基本信息的检索
package com.frank.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.frank.obj.EmployeeObj;
import com.frank.rule.EmployeeDAO;
public class SearchServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public SearchServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String employeeName=request.getParameter("employeeName");
EmployeeDAO employeeDAO=new EmployeeDAO();
EmployeeObj employeeObj=employeeDAO.getEmployeeByName(employeeName);
HttpSession session=request.getSession();
session.setAttribute("employee", employeeObj);
response.sendRedirect("display.jsp");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
此Servlet调用业务类的getEmployeeByName方法检索人员基本信息,返回EmployeeObj对象,并放入session中,当然也可以放入request中,根据自己的需要改进。页面检索成功后重定向到display.jsp进行信息的显示(稍后讲解)
getEmployeeByName方法代码如下:
public EmployeeObj getEmployeeByName(String employeeName){
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
EmployeeObj employeeObj=new EmployeeObj();
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
String strSQL="SELECT employeeId,employeeName,age FROM EmployeeInfo WHERE employeeName=?";
pstmt=conn.prepareStatement(strSQL);
pstmt.setString(1, employeeName);
rst=pstmt.executeQuery();
if(rst.next()){
employeeObj.setEmployeeId(rst.getInt("employeeId"));
employeeObj.setEmployeeName(rst.getString("employeeName"));
employeeObj.setAge(rst.getInt("age"));
return employeeObj;
}
return null;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return null;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}finally{
try{
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
display.jsp负责显示查询出的结果信息,代码如下:
<%@ page language="java" import="java.util.*,com.frank.obj.*" pageEncoding="ISO-8859-1"%>
<%
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 'display.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">
-->
<%
EmployeeObj employeeObj=(EmployeeObj)session.getAttribute("employee");
%>
</head>
<body>
<table width="80" border="15">
<tr>
<td width="30%" align="right">EmployeeId</td>
<td width="70%" align="left"><%=employeeObj.getEmployeeId() %></td>
</tr>
<tr>
<td width="30%" align="right">EmployeeName</td>
<td width="70%" align="left"><%=employeeObj.getEmployeeName() %></td>
</tr>
<tr>
<td width="30%" align="right">Age</td>
<td width="70%" align="left"><%=employeeObj.getAge() %></td>
</tr>
<tr>
<td width="30%" align="right">Pic</td>
<td width="70%" align="left"><img src="displayServlet?employeeId=<%=employeeObj.getEmployeeId() %>"/></td>
</tr>
</table>
</body>
</html>
代码非常的简单,只是简单的从session中获取保存的EmployeeObj对象,然后利用jsp表达式将数据成员信息显示到页面上。但是注意粗体部分,因为我们需要将保存的图片数据读出,然后显示成图片。所以在此我们利用Img元素显示图片,而Src利用displayServlet的运行结果输出到客户端,作为图片的显示源。displayServlet包含参数employeeId,用来决定具体显示哪一员工的图片。
displayServlet通过Servlet输出流,将读取的图片数据发送到客户端,代码如下:
package com.frank.action;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.frank.rule.EmployeeDAO;
public class DisplayServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public DisplayServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/gif");
int employeeId=Integer.parseInt(request.getParameter("employeeId"));
EmployeeDAO employeeDAO=new EmployeeDAO();
InputStream is=employeeDAO.getPicById(employeeId);
int size=is.available();
byte[] image=new byte[size];
is.read(image);
ServletOutputStream out=response.getOutputStream();
out.write(image);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
在此,调用业务类的getPicById方法得到图片数据的输入流。然后获取的输入流写到ServletOutputStream,这样可以在Servlet的输出端使用,即img的src中使用
getPicById代码如下:
public InputStream getPicById(int employeeId){
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
InputStream is=null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
String strSQL="SELECT pic FROM EmployeeInfo WHERE employeeId=?";
pstmt=conn.prepareStatement(strSQL);
pstmt.setInt(1, employeeId);
rst=pstmt.executeQuery();
if(rst.next()){
is=rst.getBinaryStream("pic");
return is;
}
return null;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return null;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}finally{
try{
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
注意粗体部分
好了,我们可以通过运行结果来进行验证,假设我们搜索名称为Mike的人员数据,那么这样:
点search按钮,运行结果如下:
好了,显示出了检索结果,不但包括人员的基本数据,保存到数据库中的图片数据也被读出并显示成图片。
代码只是利用jsp简单的进行体现,大家可以根据自己的需要进行改进。
- FileUpload.zip (212.9 KB)
- 下载次数: 0
- ImagesUpload_图片上传源码_.zip (773.5 KB)
- 下载次数: 0
发表评论
-
myeclipse项目上有红叉问题
2017-01-03 08:36 419Java compiler level does not m ... -
java总结(基础知识-面试)
2016-05-13 14:27 994lJava发射(案例) l反射含义: lJAVA反射机制 ... -
文件上传
2016-05-20 10:39 277在实际的开发中,我们可能需要将图片、影音等文件直接保存到数据 ... -
Servlet的运行过程
2016-09-20 20:28 467一、Servlet简介 Servlet是sun公司提供 ... -
Java序列化与反序列化
2016-09-06 21:59 437Java序列化与反序列化是什么?为什么需要序列化与反序列化 ...
相关推荐
基于SpringBoot的文件上传系统,前后端分离,单文件上传,多文件上传,大文件上传,断点续传,文件秒传,图片上传 项目经过严格测试,确保可以运行! 采用前后端分离的方式进行开发,实现了几种常用的文件上传功能...
之前发布一个大文件上传,但是问题太多,此版本相对上一个稳定得多 1,将压缩包里的 php_uploadprogress.dll 文件复制到你的PHP 安装目录里的扩展库文件夹 就是 ext文件夹下面 2,在你的服务器上随便一个地方(最好...
在Vue.js中,实现文件上传功能是常见的需求,尤其是在构建交互丰富的Web应用时。本篇将详细介绍Vue.js中实现多文件上传的相关知识点,以及如何使用`vue-upload-component`这个开源组件来帮助我们实现这一功能。 ...
为了简化这个过程,开发者通常会编写一个专门的文件上传类,以实现对上传过程的全面控制和错误处理。以下是对"PHP文件上传类"的详细解析: 1. **类的结构**: - 一个PHP文件上传类通常包含一系列的方法,如`upload...
在Java开发中,文件上传和下载是常见的功能需求,尤其在网络应用中,如网页、桌面应用或移动应用。为了实现这些功能,开发者通常需要引入特定的库或jar包。在这个场景下,"文件上传下载需要的jar包"指的是用于处理...
在Java开发中,多文件上传是一项常见的功能,尤其在Web应用中,用户可能需要一次性上传多个文件,如图片、文档等。本知识点将详细介绍如何在Java中实现这一功能,以及结合Flash实现上传界面并显示上传进度条。 1. *...
本想做个批量文件上传的功能(设想是客户选择一个目录后,程序能判断需要上传的文件上传到服务器指定目录下),结果没有做出来,在网上找了许多版本的批量上传程序,但实验效果不好,有的还需要下载分,上传文件也不能...
在这个“SpringMVC文件上传,多文件上传实例”中,我们将深入探讨如何在SpringMVC环境中实现文件上传功能,包括单个文件上传以及多个文件的批量上传。 1. **文件上传原理**: 文件上传是通过HTTP协议的POST请求来...
- **多文件上传**:支持单个文件和批量文件上传,提高用户操作效率。 2. **使用方法** 首先,你需要将压缩包中的PHP文件解压到你的项目目录中。然后,在需要实现文件上传功能的PHP脚本中引入该插件,通过调用其...
Bootstrap文件上传组件FileInput是一款强大的前端文件上传工具,尤其适合于需要实现文件批量上传的场景。这个组件基于Bootstrap框架,提供了美观的用户界面和丰富的功能,使得文件上传操作变得直观且易于实现。以下...
在.NET框架中,C#语言提供了丰富的功能来处理文件上传操作。对于初学者来说,理解并实现多文件上传是一项重要的技能,它可以帮助你构建交互性强、功能完善的Web应用程序。在这个"C# .NET FileUpload 多文件上传例子...
使用这个插件,开发者可以轻松集成到自己的项目中,实现高效、友好的文件上传功能。 HTML5文件上传的核心特性包括: 1. **多文件选择**:通过`<input type="file" multiple>`,用户可以在文件选择对话框中选取多个...
【标题】:多文件上传和展示 在网页开发中,多文件上传功能是常见的需求,尤其是在数据管理和资源共享的场景下。Bootstrap-fileinput 是一个流行的、功能丰富的jQuery插件,专门用于实现美观且实用的文件上传功能,...
在网络上找到的,纯JSP实现的文件上传程序,支持多文件的上传,例子是多文件的上传,稍微修改就可以变成单文件的上传或者更多文件的上传,控制成需要扩展名的文件上传,指定大小的文件上传等。程序目前上传文件存储...
"JSP多文件上传"是一个常见的需求,特别是在文件分享、在线教育或文档管理等场景。这个功能允许用户一次性选择并上传多个文件,提高了用户体验,减少了多次点击和等待时间。 实现JSP多文件上传,我们需要了解以下几...
这个功能对于处理大量文件上传的场景非常有用,比如在内容管理系统、图像库或者文件分享平台等应用中。 `MultiFileUploadField` 的核心特点包括: 1. **多选支持**:用户可以通过浏览器的文件选择对话框一次选择多...
在Android开发中,文件上传,特别是图片上传,是常见的需求之一。这涉及到用户选择本地文件,通常是图片,然后通过网络接口将这些文件发送到服务器。本文将深入探讨如何实现Android平台上的多文件和单文件上传,以及...
总之,"通用 万能 HttpHandler webRequest 文件上传"是一个关于使用自定义HttpHandler和HttpWebRequest进行文件上传的技术主题。这个解决方案旨在提供一个高度可定制和可扩展的文件上传服务,以满足各种Web应用的...
在IT领域,尤其是在Web开发中,文件上传是一个常见的需求,特别是在处理大文件如高清图片、视频或大型文档时。jQuery,作为一个广泛使用的JavaScript库,提供了一系列的插件来解决这个问题。"jquery-大文件上传插件...
接着,实现大文件上传的关键在于分块处理。我们可以将大文件分割成多个小块,然后逐个上传。这种方式降低了单次请求的压力,有利于网络不稳定时的恢复。PHP中,可以通过`fread()`函数读取文件的特定部分,`cURL`库则...