首页 »Java教程 » struts1.2:Struts1.2实现MySQL数据库分页 »正文
struts1.2:Struts1.2实现MySQL数据库分页
来源: 发布时间:星期四, 2009年1月15日 浏览:24次 评论:0
我 平台是:Eclipse3.2 MyEclipse5.5 Tomcat5.5 MySql5.0 第 步:创建数据库: 这没什么难 用下面 脚本就OK了 CREATEDATABASEpage; usepage; CREATETABLE `product` ( `id` varchar(11) NOTNULL, `sortid` varchar(11) NOTNULL, `name` varchar(50) NOTNULL, `price` doubleNOTNULL, `saleprice` doubleNOTNULL, `descript` text NOTNULL, `contents` text NOTNULL, `saledate` varchar(255) NOTNULL, `salecount` (11) defaultNULL, `image` text, PRIMARYKEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 第 2步:创建 个项目 创建 个项目,项目名为”strutsPage”,导入Struts1.2 Struts 包采用默认 引用MySql 驱动 要是没有驱动 话 请到http://download.csdn.net/source/400716这下载 下面设置web.xml和struts-config.xml配置文件 我觉得直接COPY我 就好了 web.xml:文件里 内容如下 直接换上就OK了 基本是默认 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>action</servlet-name> <servlet->org.apache.struts.action.ActionServlet</servlet-> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
struts-config.xml 内容如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans /> <global-exceptions /> <global-forwards /> <action-mappings > <action attribute="productShowForm" input="/index.jsp" name="productShowForm" path="/productShow" scope="request" type="com.yourcompany.struts.action.ProductShowAction"> <forward name="success" path="/index.jsp" /> </action> </action-mappings> <message-resources parameter="com.yourcompany.struts.ApplicationResources" /> </struts-config> 第 3步:创建包和数据库连接 在SRC下创建 dao , dbtool, vo,factory 4个包 在dbtool包里主要放访问JDBC数据库 连接类等 下面提供我用 JavaBean类 DBConnection.java 内容如下: package com.yourcompany.dbtool; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * 这是个连接数据单模式 * @author 树下无影 * */ public DBConnection { private DBConnection instance; private String driver; private String url; private String user; private String password; private DBConnection throws Exception{ InputStream in=getClass.getClassLoader.getResourceAsStream( "com/yourcompany/dbtool/database.properties"); Properties prop= Properties; prop.load(in); driver=prop.getProperty("driver"); url=prop.getProperty("url"); user=prop.getProperty("user"); password=prop.getProperty("password"); try{ Class.forName(driver); }catch(Exception e) { .out.prln("数据库化出错"); throw e; } .out.prln(driver+" "+url+" "+user+" "+password); } public DBConnection getInstance{ try{ (instancenull){ instance= DBConnection; } instance; }catch(Exception e){ .out.prln("例子化单模子出错"); null; } } public Connection getConnectionthrows SQLException{ Connection con; try{ con=DriverManager.getConnection(url, user, password); }catch(SQLException e){ .out.prln("Connection连接出错"); throw e; } con; } public void closeConnection(Connection con){ (con!=null){ try{ con.close; }catch(SQLException e) { .out.prln("关闭Connection连接出错"); } } } }
这里用 个配置文件 database.properties 里面存放数据库 URL 、Driver、Username和Password等 修改成你本机 相应数据 能打开数据库就好 database.properties内容如下: driver=org.gjt.mm.mysql.Driver url=jdbc:mysql://localhost:3306/page user=root password=1234 下面是我用 数据库增删改查 Bean-> DBbusiness.java package com.yourcompany.dbtool; import java.sql.*; /** * 这是个连接数据库具有增删改查Bean * @author 树下无影 * */ public DBbusiness { /* * 定义连接参数等 */ Connection conn = null; PreparedStatement psps = null; ResultSet rs = null; public DBbusiness { } /* * 定义公用Connection */ public Connection getConn { try { DBConnection db=DBConnection.getInstance; Connection conx = db.getConnection; conx; } catch (Exception e) { .out.prln("Connection连接出错"); } null; } /* * 获取数据(查询)思路方法 */ public ResultSet getData(String sql) { try { conn = getConn; psps = conn.prepareStatement(sql); rs = psps.executeQuery; } catch (Exception e) { .out.prln("查询数据库操作出错"); } rs; } /* * 定义插入数据和更新思路方法 */ public boolean insert(String sql) { try { conn = getConn; psps = conn.prepareStatement(sql); psps.executeUpdate; true; } catch (Exception e) { .out.prln("数据库更新出错"); } false; } /* * 定义创建数据库和表思路方法 */ public boolean create(String sql) { try { conn = getConn; psps = conn.prepareStatement(sql); psps.execute; true; } catch (Exception e) { } false; } /* * 定义关闭连接思路方法 */ public void allClose { try { (rs != null) rs.close; (psps != null) psps.close; (conn != null) { DBConnection db=DBConnection.getInstance; db.closeConnection(conn); } } catch (Exception e) { .out.prln("数据库关闭操作出错"); } } }
第 4步:创建实体类 在vo包里 创建 个实体类 这步COPY过去就是 Product.java package com.yourcompany.vo; public Product { String id; String sortid; String name; String price; String saleprice; String descript; String contents; String saledate; String salecount; String image; public Product{} public Product(String id,String sortid,String name,String price, String saleprice,String descript,String contents, String saledate,String salecount,String image){ this.id=id; this.sortid=sortid; this.name=name; this.price=price; this.saleprice=saleprice; this.descript=descript; this.contents=contents; this.saledate=saledate; this.salecount=salecount; this.image=image; } public String getContents { contents; } public void Contents(String contents) { this.contents = contents; } public String getDescript { descript; } public void Descript(String descript) { this.descript = descript; } public String getId { id; } public void Id(String id) { this.id = id; } public String getImage { image; } public void Image(String image) { this.image = image; } public String getName { name; } public void Name(String name) { this.name = name; } public String getPrice { price; } public void Price(String price) { this.price = price; } public String getSalecount { salecount; } public void Salecount(String salecount) { this.salecount = salecount; } public String getSaledate { saledate; } public void Saledate(String saledate) { this.saledate = saledate; } public String getSaleprice { saleprice; } public void Saleprice(String saleprice) { this.saleprice = saleprice; } public String getSortid { sortid; } public void Sortid(String sortid) { this.sortid = sortid; } }
第 5步:创建接口 并创建相应 实现类 PageDao.java接口里有两个思路方法,第 个思路方法是读取指定数据表 行数;第 2个思路方法是读取数据表 并把信息放入 个ArrayList返回 看代码 package com.yourcompany.dao; import java.util.ArrayList; import java.util.List; public erface PageDao { public getCount(String counSql); public ArrayList getProduct(String sql); } 创建接口好后 当然要创建实现类 如下:PageDaoImpl.java package com.yourcompany.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.yourcompany.dbtool.DBbusiness; import com.yourcompany.vo.Product; /** * 这是接口实现类 * @author 树下无影 * */ public PageDaoImpl implements PageDao { /* * 获取数据行数 * @see com.yourcompany.dao.PageDao#getCount(java.lang.String) */ public getCount(String counSql){ result=0; DBbusiness db= DBbusiness; ResultSet rs= db.getData(counSql); try { rs.next; result=rs.getInt(1); /*while(rs.next){ result=rs.getInt(1); }*/ } catch (SQLException e) { // TODO Auto-generated catch block .out.prln("读取数据总数失败"); }finally{ db.allClose; } result; } /* * 读取数据表 */ public ArrayList getProduct(String sql){ ArrayList .gif' />List= ArrayList; DBbusiness db= DBbusiness; ResultSet rs=db.getData(sql); try { while(rs.next){ String id=rs.getString(1); String sortid=rs.getString(2); String name=rs.getString(3); String price=rs.getString(4); String saleprice=rs.getString(5); String descript=rs.getString(6); String contents=rs.getString(7); String saledate=rs.getString(8); String salecount=rs.getString(9); String image=rs.getString(10); Product productForm= Product( id,sortid ,name, price, saleprice ,descript, contents, saledate,salecount,image); .gif' />List.add(productForm); } } catch (SQLException e) { // TODO Auto-generated catch block .out.prln("数据库读取出错"); }finally{ db.allClose; } .gif' />List; } }
第 6步:创建映射 工厂类: 这个类没什么解释 放在factoyr 包里 PageDaoFactory.java package com.yourcompany.factory; import com.yourcompany.dao.PageDao; import com.yourcompany.dao.PageDaoImpl; public PageDaoFactory { public PageDao getPageDaoIntanse{ PageDaoImpl; } } 第 7步:分页处理类 呵呵 这么多步骤了还没进入正题 下面就开始讲和分页相关 在dbtool包里创建如下类: PageBean.java package com.yourcompany.dbtool; import com.yourcompany.factory.PageDaoFactory; public PageBean { /** * 这是个分页类MySQL数据库检索可以使用分页SQL指令 * 所在在这里主要是处理出这样指令 * 并获得相应页数信息 *MySql语句如下:select * from test limit 10;这句是从1到10信息条数 *select * from test limit 10,5; 这句是第十条以后 5条 */ curr; //当前页 count; //总页数 size; //每页显示数据数 rows=0; //数据所有行数 boolean last; // 是否是最后页 /** * 构造器 * @param counSql */ public PageBean(String counSql) { (this.rows 0) {//获取所有数据条数 this.rows = PageDaoFactory.getPageDaoIntanse.getCount(counSql); } this.curr=getCurr; this.size = 5;//设定页面显示数据大小 this.count = () Math.ceil((double) this.rows / this.size);//获得页数 this.last=isLast; } public PageBean(String counSql, size){ (this.rows 0) {//获取所有数据条数 this.rows = PageDaoFactory.getPageDaoIntanse.getCount(counSql); } this.curr=getCurr; this.size = size;//设定页面显示数据大小 this.count = () Math.ceil((double) this.rows / this.size); this.last=isLast; } public PageBean(String counSql, curr, size){ (this.rows 0) {//获取所有数据条数 this.rows = PageDaoFactory.getPageDaoIntanse.getCount(counSql); } this.curr=curr; this.size = size;//设定页面显示数据大小 this.count = () Math.ceil((double) this.rows / this.size); this.last=isLast; } /** * 页面指令处理及返回相应查询SQL语句 */ public String pageDeal(String pageDo, String sql) { String str = " limit "; //首页 (pageDo.equals("first")) { Curr(1); str "" + getSize; } //尾页 (pageDo.equals("end")) { Curr(getCount); str "" + ((getCount - 1) * getSize); str "," + (getRows - (getCount - 1) * getSize); } //下页 (pageDo.equals("next")) { (getCurr<getCount){ str "" + (getCurr * getSize); str "," + getSize; Curr(getCurr + 1); }{ Curr(getCount); str "" + ((getCount - 1) * getSize); str "," + (getRows - (getCount - 1) * getSize); } } //上页 (pageDo.equals("prv")) { Curr(getCurr - 1); str "" + (getCurr * getSize - getSize); str "," + getSize; } sql + str; } public void (String args) { } //返回总页数总页最小也等于1 public getCount { (count 0) ? 1 : count; } //设置总页数 public void Count( count) { this.count = count; } //返回当前页,当前页最小也等于1 public getCurr { (curr 0) ? 1 : curr; } //设置当前页 public void Curr( curr) { this.curr = curr; } public getRows { rows; } public void Rows( rows) { this.rows = rows; } public getSize { size; } public void Size( size) { this.size = size; } /** * 如果是最后页返回true * @ */ public boolean isLast { (currcount)?true:false; } public void Last(boolean last) { this.last = last; } }
这个类写了很多 注释 不过还是要讲解 下 由于在Struts Action里用到第 3个构造器 那就先讲这个吧 构造器里主要 功能是 通过Factory映射 接口类 读取数据表 行数 获得表 所有行数 然后和传进来 页面显示信息数除 下 就获得页数 总数了 当前页 定义 要是第 次读取 当前页当然是第 页了 要是点了下 页 当前页就加 页 点上 页 当前页就减 面 嘿嘿 我这里主要由页面传当前页进来 再根据传进来 动作进行处理当前页 所以“下 页”这样 动作除了要传 个动作外还要传当时 当前页 Action 里通过 pageDeal(“” “”)这思路方法就就可以获取相应 分页处理了 当然还要加上”select * from table”这样 语句才能实现 好了 看下 步Action里是怎样处理 第 8步:Action 处理: 在struts.action 包里创建如下类: package com.yourcompany.struts.action; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.yourcompany.dbtool.PageBean; import com.yourcompany.factory.PageDaoFactory; import com.yourcompany.vo.Product; public ProductShowAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ArrayList aList = ArrayList; /* * 定义页面传过来动作如点"下页" 并这动作而决定处理 */ String pageDo = request.getParameter("pageDo"); /* * 定义获取页面传过来当前页getCurr */ getCurr; String curr_page = request.getParameter("curr_page"); (curr_page null || curr_page.equals("")) { getCurr = 1; } { getCurr = Integer.parseInt(request.getParameter("curr_page")); .out.prln(getCurr); } /* * 例子化PageBean对象 * PageBean有几个构造器不过都要传送句获取数据库行数SQL语句 * getCurr是传送个当前页给PageBean构造器 * 2是定义每页显示几行数据 */ PageBean pb = PageBean("select count(*) from product", getCurr, 2); // 定义查询数据库SQL语句格式如下 String sql; sql = pb.pageDeal(pageDo, "select * from product "); // 定义ArrayList获取数据库所查询得到数据 aList = PageDaoFactory.getPageDaoIntanse.getProduct(sql); // 把值传给客户端 request.Attribute("pageInfo", pb); request.Attribute("data", aList); mapping.findForward("success"); } }
这个Action里也写了好多 注释 相信 看就明白 步骤主要是: 1.定义两个参数 获取前台传进来 动作和当前页 2.例子化分页 处理类 PageBean.java 在它 构造器里传进查询数据库行数 SQL语句、当前页、要在表里显示 规格 3.获取处理好 分页SQL语句 主要是 PageBean里 pageDeal思路方法 给它传进 是页面传进来 动作和查询数据表 SQL语句 4.用处理好 分布SQL语句去查询数据 5.把值传给前台 主要返回PageBean 对象和所查询得 数据ArrayList 第 9步:前台处理页面 由于后台传回来 是 个ArrayList 数据表 所以把它读出来就是 还返回 个PageBean 对象 这里包含 数据是当前页、总页、是否为最后 页 所以要是想弄区别 “上 页”、“下 页”这样 导航条 话 修改传回 参数 再在Jsp页面里做相应 处理就OK了 看我 Jsp页面:index.jsp <%@ page language="java" pageEncoding="utf-8"%> <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %> <%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %> <% (session.getAttribute("getData")null) {//这里只是个跳转没什么 session.Attribute("getData","ok"); response.Header("refresh", "1;url=/strutsPage/productShow.do?pageDo=first&curr_page=1"); } %> <html> <head> <title>JSP for ProductShowForm form</title> </head> <body><font color="#0000ff"> 这里仅演示分页操作部分已经做到获取ID了相信直接就可以弄修改和删除</font> <table width="80%" border="1"> <tr> <th> 商品名称 </th> <th> 价格 </th> <th> 商品描述 </th> <th> 商品详细信息 </th> <th > 上架日期 </th> <th colspan="2" align="center"> 操作 </th> </tr> <logic:present name="data" scope="request"> <logic:iterate id="show" name="data" type="com.yourcompany.vo.Product"> <tr> <td> <bean:write name="show" property="name" /> </td> <td> <bean:write name="show" property="saleprice" /> </td> <td> <bean:write name="show" property="descript" /> </td> <%--<td> <bean:write name="show" property="contents" /> </td> --%><td > <bean:write name="show" property="saledate" /> </td> <td> <html:link action="/productShow.do?pageDo=updata" paramId="up_page" paramName="show" paramProperty="id"> 修改</html:link> </td> <td> <html:link action="/productShow.do?pageDo=dele" paramId="dele_page" paramName="show" paramProperty="id"> 删除</html:link> </td> </tr> </logic:iterate> </logic:present> </table> <logic:present name="pageInfo"> 第<bean:write name="pageInfo" property="curr" />页/共 <bean:write name="pageInfo" property="count" />页. <html:link action="/productShow.do?pageDo=first" paramId="curr_page" paramName="pageInfo" paramProperty="curr"> 首页</html:link> <logic:notEqual name="pageInfo" property="curr" value="1"> <html:link action="/productShow.do?pageDo=prv" paramId="curr_page" paramName="pageInfo" paramProperty="curr"> 上页</html:link> </logic:notEqual> <logic:equal name="pageInfo" property="last" value="false"> <html:link action="/productShow.do?pageDo=next" paramId="curr_page" paramName="pageInfo" paramProperty="curr"> 下页</html:link> </logic:equal> <html:link action="/productShow.do?pageDo=end" paramId="curr_page" paramName="pageInfo" paramProperty="curr"> 尾页</html:link> </logic:present> </body> </html> 整理总结: 这个分页看起来很简单 做起来也很简单 只是对SQL语句做了 下过滤而已 这个分页功能很简单 但重在抛砖引玉!
相关文章
读者评论
发表评论
|
|