- 浏览: 241627 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
bihailantian_:
[/size]我而且额 ...
得到集合中的最后一条记录&和求基数偶数 -
w327569056w:
能发一份吗??谢谢 303430060@qq.com
在线购物系统毕业论文 &图书管理系统毕业论文 -
yuan23:
在线购物的系统,谢谢,464302726@qq.com ...
在线购物系统毕业论文 &图书管理系统毕业论文 -
君心可晴:
作业相关
想参考参考
1035236640@qq.com
LZ ...
在线购物系统毕业论文 &图书管理系统毕业论文 -
smith789:
该交论文了,题目相近,感谢博主!smith5623@126.c ...
在线购物系统毕业论文 &图书管理系统毕业论文
在实际的开发中,我们可能需要将图片、影音等文件直接保存到数据库中,然后通过编程方式将数据读出进行使用。例如将读出的图片数据显示出来,将读出的电影文件播放出来。
二进制数据直接保存到文件和从文件中读出非常的简单。和普通的数据库操作差别不大。只是用到部分流操作。例如各种输入输出流操作。所以深刻理解流操是非常重要的。
在此我借助于一个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中,以便页面使用。
JOPO类(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中,以便页面使用。
JOPO类(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简单的进行体现,大家可以根据自己的需要进行改进
---很抱歉截图不可以在这个上面显示 ----
发表评论
-
Unable to load configuration. - package
2011-02-16 10:00 2263Unable to load configuration. - ... -
中文乱码问题
2010-10-08 17:57 1350Char流向byte流的错误转换 byte流向Cha ... -
ERROR [AjpMessage] Invalid message recieved with signature 18245
2010-07-29 15:37 4944ERROR [AjpMessage] Invalid mess ... -
Context startup failed due to previous errors
2010-07-29 13:03 8109严重: Context [/app] startup fail ... -
线程异常终止
2010-06-29 18:36 1269最近在做一个项目时用到了多线程,开启一定数量的线程无限循环交 ... -
Page-encoding specified in XML prolog (UTF-8)
2010-05-29 12:49 3025在用记事本修改jsp 页面时 如果jsp的第一行是编码格式就有 ... -
java.util.ConcurrentModificationException 原由
2010-05-16 11:46 5383用iterator遍历集合时要注意的地方:不可以对iterat ... -
JBOSS 内存溢出
2010-05-08 22:05 5622前几天做EXCEL导出数据,发现当数据量达到一定的时候会报内 ... -
java.net.SocketException: Broken pipe
2010-04-25 23:17 2682java.net.SocketException: Broke ... -
教大家如何更好的使用HashMap
2010-04-12 23:16 1584先来看一个例子:将Student作为key HomeInfo作 ... -
从JKS文件中读取密钥
2010-04-11 16:37 4825JKS文件是一个java中的密钥管理库,里面可以放各种密钥文件 ... -
struts2的action调用
2010-02-03 16:38 11401、Action类: public class IndexA ... -
解决struts2传值到action乱码问题
2009-04-09 11:44 5640这两天在研究struts2,页面给aciton传值时乱 ... -
二叉树 添加和查找
2009-03-13 15:38 1682------------ 前几天闲下来时间做的一个二叉树的小例 ... -
两个下拉框 左框添加值右框删除值
2008-11-07 17:24 1472<!DOCTYPE html PUBLIC " ... -
java自定义标签代码
2008-04-25 10:15 2063--------------------javaBean--- ... -
下拉框点击事件&JS操作
2008-04-23 17:40 15936前几天遇到一个问题:当你点击一个选择下拉框内容时,另一个地方显 ... -
推荐一个好的java学习网站
2008-02-15 11:57 1803我写博客不为什么 只为自己能把学到的东西毫无保留的写在上面 以 ... -
面向对象概念之一:封装
2007-09-04 14:53 3248封装:Encapsulation 是 ...
相关推荐
本教程将深入探讨如何在Java环境下,批量地从MySQL数据库中下载存储在Blob字段中的图片,并将其保存到本地文件系统。 首先,我们需要理解Blob类型。Blob是MySQL中的一个数据类型,用于存储大量二进制数据。它分为四...
通过本源码可以了解到Java如何产生单钥加密的密钥(myKey)、产生双钥的密钥对(keyPair)、如何保存公钥的字节数组、保存私钥到文件privateKey.dat、如何用Java对象序列化保存私钥,通常应对私钥加密后再保存、如何从...
// 图片保存逻辑,例如保存到指定目录,并返回保存后的URL String savePath = saveImage(file); return "{\"error\":0,\"url\":\"" + savePath + "\"}"; } ``` 4. **内容提交**:编辑器中的内容可以通过AJAX提交...
// 这里可以进一步处理base64String,例如保存到数据库、发送网络请求等 } catch (IOException e) { System.err.println("Error reading PDF file: " + e.getMessage()); } ``` 此外,如果需要解码回原始的PDF文件...
通过本源码可以了解到Java如何产生单钥加密的密钥(myKey)、产生双钥的密钥对(keyPair)、如何保存公钥的字节数组、保存私钥到文件privateKey.dat、如何用Java对象序列化保存私钥,通常应对私钥加密后再保存、如何从...
通过本源码可以了解到Java如何产生单钥加密的密钥(myKey)、产生双钥的密钥对(keyPair)、如何保存公钥的字节数组、保存私钥到文件privateKey.dat、如何用Java对象序列化保存私钥,通常应对私钥加密后再保存、如何从...
通过本源码可以了解到Java如何产生单钥加密的密钥(myKey)、产生双钥的密钥对(keyPair)、如何保存公钥的字节数组、保存私钥到文件privateKey.dat、如何用Java对象序列化保存私钥,通常应对私钥加密后再保存、如何从...
通过本源码可以了解到Java如何产生单钥加密的密钥(myKey)、产生双钥的密钥对(keyPair)、如何保存公钥的字节数组、保存私钥到文件privateKey.dat、如何用Java对象序列化保存私钥,通常应对私钥加密后再保存、如何从...
通过本源码可以了解到Java如何产生单钥加密的密钥(myKey)、产生双钥的密钥对(keyPair)、如何保存公钥的字节数组、保存私钥到文件privateKey.dat、如何用Java对象序列化保存私钥,通常应对私钥加密后再保存、如何从...
通过本源码可以了解到Java如何产生单钥加密的密钥(myKey)、产生双钥的密钥对(keyPair)、如何保存公钥的字节数组、保存私钥到文件privateKey.dat、如何用Java对象序列化保存私钥,通常应对私钥加密后再保存、如何从...
在描述中提到的场景是,一个项目需要在文档中添加可识别的元素,比如条形码,然后将包含这些元素的文档作为图像保存到数据库中,以避免二次扫描的步骤。在寻找解决方案的过程中,开发者发现大部分JasperReport的示例...
本教程通过"Image Save To Sql And Display.wmv"视频,详细讲解了如何将图片保存到Microsoft SQL Server数据库中,并且如何在应用程序中展示这些图片。这一过程涉及到的关键知识点包括: 1. 图像数据的二进制存储:...
- **保存表单数据:** 实训中将学习如何将用户提交的表单数据保存到数据库中。 - **显示数据:** 学习如何从数据库中检索数据并在网页上显示出来。 #### 六、JSP - **JSP简介:** JSP是Java Server Pages的缩写...
9. **游戏状态保存和恢复**:为了提供良好的用户体验,游戏应支持保存进度和恢复功能,这通常涉及到SharedPreferences或SQLite数据库来存储用户数据。 10. **性能优化**:随着游戏进行,泡泡数量增加,对性能的要求...
3. **数据库存储**:为了保存用户数据和聊天记录,源码中可能使用了SQLite数据库或者GreenDao这样的ORM框架。数据库操作用于本地数据的增删改查,以实现离线查看消息、好友信息等功能。 4. **消息处理**:微信的...
根据提供的文件信息,本文将详细解释如何在Android中将图片转换为数据流形式进行保存,同时探讨相关的技术细节与应用场景。 ### Android图片转换为数据流形式保存 在Android开发过程中,有时我们需要将图片以数据...
本教程中将详细讲解如何在内部存储器和外部存储器之间选择、文件存取权限申请、文件的保存、查询空间、删除等操作。 最后,数据库操作是Android应用中复杂数据处理不可或缺的环节。SQLite作为Android内置的轻量级...
这通常涉及到Servlet接收POST请求,获取编辑器发送的Markdown文本,然后将其写入到文件系统或数据库中。为了保证数据安全和可恢复性,可能还会涉及文件的备份和版本控制。 通过这个项目,开发者可以学习到如何在...
我们可以使用Bitmap对象来加载和处理这些图片,然后在onDraw()方法中将它们绘制到画布上。Bitmap提供了多种操作方法,如decodeResource()用于从资源加载图片,createBitmap()可以创建一个新的Bitmap对象,而...
在Android开发中,有时我们需要将Bitmap对象保存到设备的外部存储(如SD卡)以便后续使用或分享。本文将详细讲解如何实现这个功能,并提供一个示例代码。 首先,我们需要获取到Bitmap对象。通常,Bitmap对象可以从...