(1) FLEXIGRID与IE浏览器的兼容 ,这里需要为Table加上div标签,否则在IE中会产生JS错误。参见search.jsp。
(2) Flexigrid 插件后台获取数据转换成json串之后传到前台 ,所以需要在项目中引入JSONObject相关插件包。
该插件的查询以及排序功能可以参考SearchAction类中的代码。
(3) 实现PDF与图片文件的预览与下载功能 ,参见SearchAction.java。
(4) 使用Flexigrid进行条件查询 。在前台JSP页面中添加form表单,需要注意的是,form表单中不能缺少name属性。否者Flexigrid无法获得form中的参数。
本文只是针对Flexigrid插件的基本用法,如分页、排序、条件查询进行了简单展示, 至于Flexigrid的详细用法及参数讲解,还请参考官网文档。希望本文对大家有所帮助。
首先,在Mysql中建立表GCIB ,如下:
CREATE TABLE `gcib` ( `id` int(11) NOT NULL, `name` varchar(45) default NULL, `file` mediumblob, `filetype` varchar(45) default NULL, PRIMARY KEY (`id`) )
下面是此Demo的详细代码:
<!-- Standard Action Servlet Configuration --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <!-- Standard Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
<struts-config> <!-- Form beans Definitions --> <form-beans> <form-bean name="gcibForm" type="com.form.GcibBean" ></form-bean> </form-beans> <!-- Action Mapping Definitions --> <action-mappings> <action path="/SearchAction" type="com.action.SearchAction" parameter="method"> </action> </action-mappings> </struts-config>
public class DBConnection {
private static Connection conn;
private final static String url = "jdbc:mysql://localhost:3306/test?unicode=true&characterEncoding=UTF-8";
private final static String user = "root";
private final static String password = "root";
private final static String DRIVER="com.mysql.jdbc.Driver";
public static Connection getConnection(){
try {
try {
Class.forName(DRIVER).newInstance();
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (SQLException e) {
System.out.println("ERROR: database connection wrong.");
}
return conn;
}
public void closeConnection() {
if (!(conn == null)) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("ERROR: database close wrong.");
}
}
}
}
/**
* GCIB class mapping the table GCIB in mysql.
* add a url property for deal with the record.
* @author Victor
*/
public class Gcib {
private int id;
private String name;
private String filetype;
private String url;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getFiletype() {
return filetype;
}
public void setFiletype(String filetype) {
this.filetype = filetype;
}
}
/**
* Manage the GCIB object.
* @author Victor
*/
public class GcibDAO {
/**
* Get the search result with pagination.
* @param paraMap
* @param start
* @param end
* @return
*/
public List<Gcib> getGcibList(Map<String,Object> paraMap,int start, int end) {
List<Gcib> folderList = new ArrayList<Gcib>();
String sql = "select id,name,filetype from gcib where 1=1 ";
//search conditions in where statement.
String idPara = (String)paraMap.get("idPara");
String namePara = (String)paraMap.get("namePara");
//flexigrid order.
String sortname = (String)paraMap.get("sortname");
String sortorder = (String)paraMap.get("sortorder");
String orderSQL = ""; //record order statement.
if(!this.isEmpty(sortname)||!this.isEmpty(sortorder)){
orderSQL= " order by " + sortname+" "+sortorder;
}
sql = sql+(!this.isEmpty(idPara)?" and id ="+idPara :"");
sql = sql+(!this.isEmpty(namePara)?" and name ='"+namePara+"'":"");
sql = sql + orderSQL;
sql = sql + " limit "+start+","+end+"";
Connection connect = DBConnection.getConnection();
Statement stmt = null;
try {
stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
Gcib gcib = new Gcib();
Integer idInt = rs.getInt("id");
gcib.setId(idInt);
gcib.setName(rs.getString("name"));
gcib.setFiletype(rs.getString("filetype"));
//String url = "<a href=\"/blank/SearchAction.do?method=showPDFandIMG&fileID="+idInt.toString()+"\" traget=\"_black\"\"><font color=\'blue\'>预览</font></a>";
//如果使用window.showModalDialog方法弹出下载文件,在IE中不好用。所以使用window.open或者上面的方法。
String url = "<a href=\"javascript:onClick=GCIB.showObject(\'"+idInt.toString()+"\')\"><font color=\'blue\'>预览</font></a>";
gcib.setUrl(url);
folderList.add(gcib);
}
} catch (SQLException e) {
e.printStackTrace();
}
return folderList;
}
/**
* Get the file in byte[].
* @param id
* @return
*/
public byte[] getDBFile(int id) {
String sqlFind = "select file from gcib where id = "+id;
byte[] pdf = null;
Connection conn = DBConnection.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlFind);
while(rs.next()){
pdf = rs.getBytes("file");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NullPointerException enull){
enull.printStackTrace();
}
return pdf;
}
/**
* Get the file in Blob.
* @param id
* @return
*/
public Blob getDBBlobFile(int id) {
String sqlFind = "select file from gcib where id = "+id;
Blob pdf = null;
Connection conn = DBConnection.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlFind);
while(rs.next()){
pdf = rs.getBlob("file");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NullPointerException enull){
enull.printStackTrace();
}
return pdf;
}
/**
* Get the total of the records.
* @return
*/
public int getTotal() {
int total = 0;
String sqlFind = "select count(*) from gcib ";
Connection conn = DBConnection.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlFind);
while(rs.next()){
total = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return total;
}
/**
* Get the filetype of the stream for download and preview the file.
* @param id
* @return
*/
public String getFileType(Integer id) {
String sqlFind = "select fileType from gcib where id = "+id;
String result = null;
Connection conn = DBConnection.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlFind);
while(rs.next()){
result = rs.getString("fileType");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NullPointerException enull){
enull.printStackTrace();
}
return result;
}
/**
* To check the string whether is empty.
* @param para
* @return
*/
private boolean isEmpty(String para){
return null==para || para.length()==0;
}
}
这里我使用的是Json-lib插件获取JSONObejct 。需要注意的是,要导入如下包到Lib中。
Json-lib jar
jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6
/**
* Action class to search records and show file.
* @author Victor
*/
public class SearchAction extends DispatchAction{
/**
* Search method.
* @param mapping
* @param form
* @param request
* @param response
*/
public void getList(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
PrintWriter writer = null;
JSONObject result = new JSONObject();
response.setContentType("text/json");
String idPara = request.getParameter("idPara"); //APP search condition.
String namePara = request.getParameter("namePara"); //APP search condition.
String sortname = request.getParameter("sortname"); //flexigrid's attribute.
String sortorder = request.getParameter("sortorder"); //flexigrid's attribute.
/*
String query = request.getParameter("query"); //flexigrid's query attribute.
String qtype = request.getParameter("qtype"); //flexigrid's query attribute.
*/
try {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
writer = response.getWriter();
Map<String,Object> paraMap = new HashMap<String,Object>();
paraMap.put("idPara", idPara);
paraMap.put("namePara", namePara);
paraMap.put("sortname", sortname);
paraMap.put("sortorder", sortorder);
GcibDAO dao = new GcibDAO();
int page = Integer.valueOf(StringUtils.defaultIfEmpty(request.getParameter("page"), "1"));
int rp = Integer.valueOf(StringUtils.defaultIfEmpty(request.getParameter("rp"), "10"));
int start = (page - 1) * rp;
int end = start + rp;
int total = dao.getTotal();
List<?> demoList = new ArrayList<Gcib>();
demoList = dao.getGcibList(paraMap,start, end);
result.put("rows", demoList);
result.put("total", total);
result.put("page", page);
result.put("rp", rp);
}catch (Exception e) {
e.printStackTrace();
} finally {
//IMPORTANT: this statement is very important for flexigrid. if without this, there will show nothing in the grid.
writer.println(result.toString());
writer.flush();
writer.close();
}
}
/**
* Show file method. For now.
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws IOException
*/
public ActionForward showPDFandIMG(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
OutputStream out = new BufferedOutputStream(response.getOutputStream());
GcibDAO dao = new GcibDAO();
String fileName = "FileName";
String fileType = "";
Blob blob = dao.getDBBlobFile(new Integer(request.getParameter("fileID")));
fileType = dao.getFileType(new Integer(request.getParameter("fileID")));
fileName = fileName + fileType;
try {
//stop IE cookie
/*response.setHeader("pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);*/
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("Content_Length", new Long(blob.length()).toString());
if (fileType.contains("pdf")) {
response.setContentType("application/pdf;charset=UTF-8");
}
if (fileType.contains("jpg")||fileType.contains("jpeg")) {
response.setContentType("image/*;charset=UTF-8");
}
//IMPORTANT: different browser different ways to deal file download and preview.
String agent = request.getHeader("USER-AGENT");
if(agent.indexOf("MSIE")==-1){
String enableName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
//IMPORTANT: attachment mean download the file;inline mean open file in browser.
response.setHeader("Content-Disposition","inline; filename=" + enableName );
}else{
response.setHeader("Content-Disposition","inline; filename=" + java.net.URLEncoder.encode(fileName,"UTF-8") );
}
BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream());
byte[] data = new byte[1024];
long k = 0;
while (k<blob.length()) {
int j = in.read(data, 0, 1024);
k+=j;
out.write(data, 0, j);
}
out.flush();
in.close();
out.close();
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
到Flexigrid 官网下载插件,并集成到项目中。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String webPath = request.getContextPath(); %> <!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>Search Page.</title> <link rel="stylesheet" type="text/css" href="<%=webPath%>/View/common/Flexigrid-master/css/flexigrid.pack.css" /> <script type="text/javascript" src="<%=webPath%>/View/common/Flexigrid-master/js/jquery-1.6.3.js"></script> <script type="text/javascript" src="<%=webPath%>/View/common/Flexigrid-master/js/flexigrid.pack.js"></script> <script type="text/javascript"> var webpath = "<%=webPath%>"; var $jQuery = $; </script> <script type="text/javascript" src="<%=webPath%>/View/search.js"></script> </head> <body> <div style="align:center;margin:0 auto;width:800px"> <div align="center" style="margin-top:20px"> <form id="queryForm" name="queryForm"> <table> <tr> <th align="center" colspan="2">Search conditions.</th> </tr> <tr> <td align="right">id:</td> <td align="left"><input type="text" id="idPara" name="idPara" /></td> </tr> <tr> <td align="right">name:</td> <td align="left"><input type="text" id="namePara" name="namePara" /></td> </tr> <tr> <td align="center" colspan="2"> <span><input type="button" id="queryBtn" value="查询"></span> <span><input type="reset" id="resetBtn" value="重置"></span></td> </tr> <tr> <td align="center" colspan="2"><font size="2">Please input your conditions to have a search, <br/>and the result will showed below.</font></td> </tr> </table> </form> </div> <!-- 考虑到FLEXIGRID对IE浏览器的兼容,这里需要为Table加上div标签,否则在IE中会产生JS错误。 --> <div id="divTable"> <table id="gcibTable" style="display: none;"></table> </div> </div> </body> </html>
var GCIB = new Object(); $jQuery().ready(function() { //bind search button to FLEXIGRID. $jQuery("#queryBtn").bind("click",GCIB.getList); }); GCIB.getList = function(){ //search conditions parameters. var params = [ {"name" : "idPara", "value" : $jQuery("#idPara").val()}, {"name" : "namePara", "value" : $jQuery("#namePara").val()} ]; $jQuery('#gcibTable').flexOptions({params : params, newp : 1}).flexReload(); $("#gcibTable").flexigrid( { url: webpath+'/SearchAction.do?method=getList', dataType: 'json', colModel : [ {display: '编号', name : 'id', width: 100, sortable: true, align: 'center'}, {display: '文件名称', name : 'name', width: 200, sortable: true, align: 'center'}, {display: '文件类型', name : 'filetype', width: 200, sortable: true, align: 'center'}, {display: '操作', name : 'url', width: 100, sortable: false, align: 'center'} ], checkbox : false, sortname: "id", sortorder: "asc", usepager: true, title: 'Results.', useRp: true, rp: 10, showTableToggleBtn: true, height:400, width:800 } ); }; //show the file which from database. GCIB.showObject= function(picId){ var url = webpath + '/SearchAction.do?method=showPDFandIMG&fileID=' + picId; url=encodeURI(url); //注释掉下面两行模态窗口代码,因为IE无法下载或显示流文件(其他浏览器ModalDialog可以) //var openStyle = "dialogHeight:600px; dialogWidth:800px; status:no; help:no; scroll:auto"; //window.showModalDialog(url, window.document, openStyle); var name = 'ShowPDF'; //open的网页名称,可为空; 但是不能有特殊字符,甚至连空格都不能有。否则会包参数无效JS错误。 var iWidth = 800; ; var iHeight = 600; var iTop = (window.screen.availHeight-30-iHeight)/2; //获得窗口的垂直位置; var iLeft = (window.screen.availWidth-10-iWidth)/2; //获得窗口的水平位置; var properties = "height="+iHeight+",width="+iWidth+",top="+iTop+",left="+iLeft+",toolbar=no,menubar=no,scrollbars=auto,resizable=no,location=no,status=no"; window.open(url, name, properties); };