Flexigrid Demo总结

原创网址:

http://diaopg.iteye.com/blog/1758695

Flexigrid Demo 详解(二)

《Flexigrid Demo 详解(一)》

Flexigrid Demo总结

(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,如下:

Gcib代码 复制代码 收藏代码
  1. CREATE TABLE `gcib` (
  2. `id` int(11) NOT NULL,
  3. `name` varchar(45) default NULL,
  4. `file` mediumblob,
  5. `filetype` varchar(45) default NULL,
  6. PRIMARY KEY (`id`)
  7. )

下面是此Demo的详细代码:

1.配置文件

Web.xml代码 复制代码 收藏代码
  1. <!-- Standard Action Servlet Configuration -->
  2. <servlet>
  3. <servlet-name>action</servlet-name>
  4. <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  5. <init-param>
  6. <param-name>config</param-name>
  7. <param-value>/WEB-INF/struts-config.xml</param-value>
  8. </init-param>
  9. <load-on-startup>2</load-on-startup>
  10. lt;/servlet>
  11. <!-- Standard Action Servlet Mapping -->
  12. <servlet-mapping>
  13. <servlet-name>action</servlet-name>
  14. <url-pattern>*.do</url-pattern>
  15. </servlet-mapping>
Struts-config.xml代码 复制代码 收藏代码
  1. <struts-config>
  2. <!-- Form beans Definitions -->
  3. <form-beans>
  4. <form-bean name="gcibForm" type="com.form.GcibBean" ></form-bean>
  5. </form-beans>
  6. <!-- Action Mapping Definitions -->
  7. <action-mappings>
  8. <action path="/SearchAction" type="com.action.SearchAction" parameter="method"> </action>
  9. </action-mappings>
  10. </struts-config>

2.Java文件

Dbconnection.java代码 复制代码 收藏代码
  1. public class DBConnection {
  2. private static Connection conn;
  3. private final static String url = "jdbc:mysql://localhost:3306/test?unicode=true&characterEncoding=UTF-8";
  4. private final static String user = "root";
  5. private final static String password = "root";
  6. private final static String DRIVER="com.mysql.jdbc.Driver";
  7. public static Connection getConnection(){
  8. try {
  9. try {
  10. Class.forName(DRIVER).newInstance();
  11. conn = DriverManager.getConnection(url, user, password);
  12. } catch (ClassNotFoundException e) {
  13. e.printStackTrace();
  14. } catch (InstantiationException e) {
  15. e.printStackTrace();
  16. } catch (IllegalAccessException e) {
  17. e.printStackTrace();
  18. }
  19. } catch (SQLException e) {
  20. System.out.println("ERROR: database connection wrong.");
  21. }
  22. return conn;
  23. }
  24. public void closeConnection() {
  25. if (!(conn == null)) {
  26. try {
  27. conn.close();
  28. } catch (SQLException e) {
  29. System.out.println("ERROR: database close wrong.");
  30. }
  31. }
  32. }
  33. }
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.java代码 复制代码 收藏代码
  1. /**
  2. * GCIB class mapping the table GCIB in mysql.
  3. * add a url property for deal with the record.
  4. * @author Victor
  5. */
  6. public class Gcib {
  7. private int id;
  8. private String name;
  9. private String filetype;
  10. private String url;
  11. public int getId() {
  12. return id;
  13. }
  14. public void setId(int id) {
  15. this.id = id;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. public String getUrl() {
  24. return url;
  25. }
  26. public void setUrl(String url) {
  27. this.url = url;
  28. }
  29. public String getFiletype() {
  30. return filetype;
  31. }
  32. public void setFiletype(String filetype) {
  33. this.filetype = filetype;
  34. }
  35. }
/**
 * 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;
		}
}
Gcibdao.java代码 复制代码 收藏代码
  1. /**
  2. * Manage the GCIB object.
  3. * @author Victor
  4. */
  5. public class GcibDAO {
  6. /**
  7. * Get the search result with pagination.
  8. * @param paraMap
  9. * @param start
  10. * @param end
  11. * @return
  12. */
  13. public List<Gcib> getGcibList(Map<String,Object> paraMap,int start, int end) {
  14. List<Gcib> folderList = new ArrayList<Gcib>();
  15. String sql = "select id,name,filetype from gcib where 1=1 ";
  16. //search conditions in where statement.
  17. String idPara = (String)paraMap.get("idPara");
  18. String namePara = (String)paraMap.get("namePara");
  19. //flexigrid order.
  20. String sortname = (String)paraMap.get("sortname");
  21. String sortorder = (String)paraMap.get("sortorder");
  22. String orderSQL = ""; //record order statement.
  23. if(!this.isEmpty(sortname)||!this.isEmpty(sortorder)){
  24. orderSQL= " order by " + sortname+" "+sortorder;
  25. }
  26. sql = sql+(!this.isEmpty(idPara)?" and id ="+idPara :"");
  27. sql = sql+(!this.isEmpty(namePara)?" and name ='"+namePara+"'":"");
  28. sql = sql + orderSQL;
  29. sql = sql + " limit "+start+","+end+"";
  30. Connection connect = DBConnection.getConnection();
  31. Statement stmt = null;
  32. try {
  33. stmt = connect.createStatement();
  34. ResultSet rs = stmt.executeQuery(sql);
  35. while(rs.next()){
  36. Gcib gcib = new Gcib();
  37. Integer idInt = rs.getInt("id");
  38. gcib.setId(idInt);
  39. gcib.setName(rs.getString("name"));
  40. gcib.setFiletype(rs.getString("filetype"));
  41. //String url = "<a href=\"/blank/SearchAction.do?method=showPDFandIMG&fileID="+idInt.toString()+"\" traget=\"_black\"\"><font color=\'blue\'>预览</font></a>";
  42. //如果使用window.showModalDialog方法弹出下载文件,在IE中不好用。所以使用window.open或者上面的方法。
  43. String url = "<a href=\"javascript:onClick=GCIB.showObject(\'"+idInt.toString()+"\')\"><font color=\'blue\'>预览</font></a>";
  44. gcib.setUrl(url);
  45. folderList.add(gcib);
  46. }
  47. } catch (SQLException e) {
  48. e.printStackTrace();
  49. }
  50. return folderList;
  51. }
  52. /**
  53. * Get the file in byte[].
  54. * @param id
  55. * @return
  56. */
  57. public byte[] getDBFile(int id) {
  58. String sqlFind = "select file from gcib where id = "+id;
  59. byte[] pdf = null;
  60. Connection conn = DBConnection.getConnection();
  61. try {
  62. Statement stmt = conn.createStatement();
  63. ResultSet rs = stmt.executeQuery(sqlFind);
  64. while(rs.next()){
  65. pdf = rs.getBytes("file");
  66. }
  67. } catch (SQLException e) {
  68. e.printStackTrace();
  69. } catch (NullPointerException enull){
  70. enull.printStackTrace();
  71. }
  72. return pdf;
  73. }
  74. /**
  75. * Get the file in Blob.
  76. * @param id
  77. * @return
  78. */
  79. public Blob getDBBlobFile(int id) {
  80. String sqlFind = "select file from gcib where id = "+id;
  81. Blob pdf = null;
  82. Connection conn = DBConnection.getConnection();
  83. try {
  84. Statement stmt = conn.createStatement();
  85. ResultSet rs = stmt.executeQuery(sqlFind);
  86. while(rs.next()){
  87. pdf = rs.getBlob("file");
  88. }
  89. } catch (SQLException e) {
  90. e.printStackTrace();
  91. } catch (NullPointerException enull){
  92. enull.printStackTrace();
  93. }
  94. return pdf;
  95. }
  96. /**
  97. * Get the total of the records.
  98. * @return
  99. */
  100. public int getTotal() {
  101. int total = 0;
  102. String sqlFind = "select count(*) from gcib ";
  103. Connection conn = DBConnection.getConnection();
  104. try {
  105. Statement stmt = conn.createStatement();
  106. ResultSet rs = stmt.executeQuery(sqlFind);
  107. while(rs.next()){
  108. total = rs.getInt(1);
  109. }
  110. } catch (SQLException e) {
  111. e.printStackTrace();
  112. }
  113. return total;
  114. }
  115. /**
  116. * Get the filetype of the stream for download and preview the file.
  117. * @param id
  118. * @return
  119. */
  120. public String getFileType(Integer id) {
  121. String sqlFind = "select fileType from gcib where id = "+id;
  122. String result = null;
  123. Connection conn = DBConnection.getConnection();
  124. try {
  125. Statement stmt = conn.createStatement();
  126. ResultSet rs = stmt.executeQuery(sqlFind);
  127. while(rs.next()){
  128. result = rs.getString("fileType");
  129. }
  130. } catch (SQLException e) {
  131. e.printStackTrace();
  132. } catch (NullPointerException enull){
  133. enull.printStackTrace();
  134. }
  135. return result;
  136. }
  137. /**
  138. * To check the string whether is empty.
  139. * @param para
  140. * @return
  141. */
  142. private boolean isEmpty(String para){
  143. return null==para || para.length()==0;
  144. }
  145. }
/**
 * 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

Searchaction.java代码 复制代码 收藏代码
  1. /**
  2. * Action class to search records and show file.
  3. * @author Victor
  4. */
  5. public class SearchAction extends DispatchAction{
  6. /**
  7. * Search method.
  8. * @param mapping
  9. * @param form
  10. * @param request
  11. * @param response
  12. */
  13. public void getList(ActionMapping mapping, ActionForm form,
  14. HttpServletRequest request, HttpServletResponse response) {
  15. PrintWriter writer = null;
  16. JSONObject result = new JSONObject();
  17. response.setContentType("text/json");
  18. String idPara = request.getParameter("idPara"); //APP search condition.
  19. String namePara = request.getParameter("namePara"); //APP search condition.
  20. String sortname = request.getParameter("sortname"); //flexigrid's attribute.
  21. String sortorder = request.getParameter("sortorder"); //flexigrid's attribute.
  22. /*
  23. String query = request.getParameter("query"); //flexigrid's query attribute.
  24. String qtype = request.getParameter("qtype"); //flexigrid's query attribute.
  25. */
  26. try {
  27. request.setCharacterEncoding("UTF-8");
  28. response.setCharacterEncoding("UTF-8");
  29. writer = response.getWriter();
  30. Map<String,Object> paraMap = new HashMap<String,Object>();
  31. paraMap.put("idPara", idPara);
  32. paraMap.put("namePara", namePara);
  33. paraMap.put("sortname", sortname);
  34. paraMap.put("sortorder", sortorder);
  35. GcibDAO dao = new GcibDAO();
  36. int page = Integer.valueOf(StringUtils.defaultIfEmpty(request.getParameter("page"),"1"));
  37. int rp = Integer.valueOf(StringUtils.defaultIfEmpty(request.getParameter("rp"),"10"));
  38. int start = (page - 1) * rp;
  39. int end = start + rp;
  40. int total = dao.getTotal();
  41. List<?> demoList = new ArrayList<Gcib>();
  42. demoList = dao.getGcibList(paraMap,start, end);
  43. result.put("rows", demoList);
  44. result.put("total", total);
  45. result.put("page", page);
  46. result.put("rp", rp);
  47. }catch (Exception e) {
  48. e.printStackTrace();
  49. } finally {
  50. //IMPORTANT: this statement is very important for flexigrid. if without this, there will show nothing in the grid.
  51. writer.println(result.toString());
  52. writer.flush();
  53. writer.close();
  54. }
  55. }
  56. /**
  57. * Show file method. For now.
  58. * @param mapping
  59. * @param form
  60. * @param request
  61. * @param response
  62. * @return
  63. * @throws IOException
  64. */
  65. public ActionForward showPDFandIMG(ActionMapping mapping, ActionForm form,
  66. HttpServletRequest request, HttpServletResponse response)
  67. throws IOException {
  68. OutputStream out = new BufferedOutputStream(response.getOutputStream());
  69. GcibDAO dao = new GcibDAO();
  70. String fileName = "FileName";
  71. String fileType = "";
  72. Blob blob = dao.getDBBlobFile(new Integer(request.getParameter("fileID")));
  73. fileType = dao.getFileType(new Integer(request.getParameter("fileID")));
  74. fileName = fileName + fileType;
  75. try {
  76. //stop IE cookie
  77. /*response.setHeader("pragma", "no-cache");
  78. response.setHeader("Cache-Control", "no-cache");
  79. response.setDateHeader("Expires", 0);*/
  80. response.reset();
  81. response.setCharacterEncoding("UTF-8");
  82. response.setHeader("Content_Length", new Long(blob.length()).toString());
  83. if (fileType.contains("pdf")) {
  84. response.setContentType("application/pdf;charset=UTF-8");
  85. }
  86. if (fileType.contains("jpg")||fileType.contains("jpeg")) {
  87. response.setContentType("image/*;charset=UTF-8");
  88. }
  89. //IMPORTANT: different browser different ways to deal file download and preview.
  90. String agent = request.getHeader("USER-AGENT");
  91. if(agent.indexOf("MSIE")==-1){
  92. String enableName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
  93. //IMPORTANT: attachment mean download the file;inline mean open file in browser.
  94. response.setHeader("Content-Disposition","inline; filename=" + enableName );
  95. }else{
  96. response.setHeader("Content-Disposition","inline; filename=" + java.net.URLEncoder.encode(fileName,"UTF-8") );
  97. }
  98. BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream());
  99. byte[] data = new byte[1024];
  100. long k = 0;
  101. while (k<blob.length()) {
  102. int j = in.read(data, 0, 1024);
  103. k+=j;
  104. out.write(data, 0, j);
  105. }
  106. out.flush();
  107. in.close();
  108. out.close();
  109. }
  110. catch (SQLException e) {
  111. e.printStackTrace();
  112. }
  113. return null;
  114. }
  115. }
/**
 * 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;
	}	
}

3.前台页面及JS文件

Flexigrid官网下载插件,并集成到项目中。

Search.jsp代码 复制代码 收藏代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. <%
  3. String webPath = request.getContextPath();
  4. %>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>Search Page.</title>
  10. <link rel="stylesheet" type="text/css" href="<%=webPath%>/View/common/Flexigrid-master/css/flexigrid.pack.css" />
  11. <script type="text/javascript" src="<%=webPath%>/View/common/Flexigrid-master/js/jquery-1.6.3.js"></script>
  12. <script type="text/javascript" src="<%=webPath%>/View/common/Flexigrid-master/js/flexigrid.pack.js"></script>
  13. <script type="text/javascript">
  14. var webpath = "<%=webPath%>";
  15. var $jQuery = $;
  16. </script>
  17. <script type="text/javascript" src="<%=webPath%>/View/search.js"></script>
  18. </head>
  19. <body>
  20. <div style="align:center;margin:0 auto;width:800px">
  21. <div align="center" style="margin-top:20px">
  22. <form id="queryForm" name="queryForm">
  23. <table>
  24. <tr>
  25. <th align="center" colspan="2">Search conditions.</th>
  26. </tr>
  27. <tr>
  28. <td align="right">id:</td>
  29. <td align="left"><input type="text" id="idPara" name="idPara" /></td>
  30. </tr>
  31. <tr>
  32. <td align="right">name:</td>
  33. <td align="left"><input type="text" id="namePara" name="namePara" /></td>
  34. </tr>
  35. <tr>
  36. <td align="center" colspan="2">
  37. <span><input type="button" id="queryBtn" value="查询"></span>
  38. <span><input type="reset" id="resetBtn" value="重置"></span></td>
  39. </tr>
  40. <tr>
  41. <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>
  42. </tr>
  43. </table>
  44. </form>
  45. </div>
  46. <!-- 考虑到FLEXIGRID对IE浏览器的兼容,这里需要为Table加上div标签,否则在IE中会产生JS错误。 -->
  47. <div id="divTable">
  48. <table id="gcibTable" style="display: none;"></table>
  49. </div>
  50. </div>
  51. </body>
  52. </html>
Search.js代码 复制代码 收藏代码
  1. var GCIB = new Object();
  2. $jQuery().ready(function() {
  3. //bind search button to FLEXIGRID.
  4. $jQuery("#queryBtn").bind("click",GCIB.getList);
  5. });
  6. GCIB.getList = function(){
  7. //search conditions parameters.
  8. var params = [ {"name" : "idPara","value" : $jQuery("#idPara").val()},
  9. {"name" : "namePara","value" : $jQuery("#namePara").val()} ];
  10. $jQuery('#gcibTable').flexOptions({params : params, newp :1}).flexReload();
  11. $("#gcibTable").flexigrid(
  12. {
  13. url: webpath+'/SearchAction.do?method=getList',
  14. dataType: 'json',
  15. colModel : [
  16. {display: '编号', name : 'id', width:100, sortable: true, align: 'center'},
  17. {display: '文件名称', name : 'name', width:200, sortable: true, align: 'center'},
  18. {display: '文件类型', name : 'filetype', width:200, sortable: true, align: 'center'},
  19. {display: '操作', name : 'url', width:100, sortable: false, align: 'center'}
  20. ],
  21. checkbox : false,
  22. sortname: "id",
  23. sortorder: "asc",
  24. usepager: true,
  25. title: 'Results.',
  26. useRp: true,
  27. rp: 10,
  28. showTableToggleBtn: true,
  29. height:400,
  30. width:800
  31. }
  32. );
  33. };
  34. //show the file which from database.
  35. GCIB.showObject= function(picId){
  36. var url = webpath + '/SearchAction.do?method=showPDFandIMG&fileID=' + picId;
  37. url=encodeURI(url);
  38. //注释掉下面两行模态窗口代码,因为IE无法下载或显示流文件(其他浏览器ModalDialog可以)
  39. //var openStyle = "dialogHeight:600px; dialogWidth:800px; status:no; help:no; scroll:auto";
  40. //window.showModalDialog(url, window.document, openStyle);
  41. var name = 'ShowPDF'; //open的网页名称,可为空; 但是不能有特殊字符,甚至连空格都不能有。否则会包参数无效JS错误。
  42. var iWidth = 800; ;
  43. var iHeight = 600;
  44. var iTop = (window.screen.availHeight-30-iHeight)/2; //获得窗口的垂直位置;
  45. var iLeft = (window.screen.availWidth-10-iWidth)/2; //获得窗口的水平位置;
  46. var properties = "height="+iHeight+",width="+iWidth+",top="+iTop+",left="+iLeft+",toolbar=no,menubar=no,scrollbars=auto,resizable=no,location=no,status=no";
  47. window.open(url, name, properties);
  48. };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值