SSh结合Easyui实现Datagrid的分页显示

来源:互联网 发布:后期剪辑软件 编辑:程序博客网 时间:2024/06/06 11:40
 近日学习Easyui,发现非常好用,界面很美观。将学习的心得在此写下,这篇博客写SSh结合Easyui实现Datagrid的分页显示,其他的例如添加、修改、删除、批量删除等功能将在后面的博客一一写来。

     首先看一下要实现的效果:当每页显示5行数据:

 

 

          当每页显示10行数据,效果如下:

具体步骤:

1、下载Easyui,并搭建环境。可参照博客 http://blog.csdn.net/lhq13400526230/article/details/9148299

 

2、搭建SSH工程,整个工程的目录结构如图所示:

 

3、在Oracle数据库中创建表Student。并且输入下面6行数据,因为添加操作还没有实现,所以先在数据库表中添加数据。默认设定的值是每行5个数据,所以请至少输入6行数据,便于分页的测试。

 

4、web.xml的配置

查看源码
打印?
01<?xmlversion="1.0"encoding="UTF-8"?>
02<web-appversion="2.5"xmlns="http://java.sun.com/xml/ns/javaee"
03    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
05    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
06 
07    <!-- Sttuts2过滤器 -->
08    <filter>
09        <filter-name>struts2</filter-name>
10        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
11    </filter>
12    <filter-mapping>
13        <filter-name>struts2</filter-name>
14        <url-pattern>/*</url-pattern>
15    </filter-mapping>
16 
17    <!-- 监听器Spring -->
18    <listener>
19        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
20    </listener>
21 
22    <!-- 定位applicationContext.xml的物理位置 -->
23    <context-param>
24        <param-name>contextConfigLocation</param-name>
25        <param-value>classpath:applicationContext.xml</param-value>
26    </context-param>
27 
28</web-app>

 

 

5、applicationContext.xml的配置

查看源码
打印?
01<?xmlversion="1.0"encoding="UTF-8"?>
02<beansxmlns="http://www.springframework.org/schema/beans"
03    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
04    xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
05    xsi:schemaLocation="http://www.springframework.org/schema/beans
06           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
07           http://www.springframework.org/schema/context
08           http://www.springframework.org/schema/context/spring-context-2.5.xsd
09           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
10           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
11 
12 
13 
14<importresource="applicationContext_bean.xml"/>
15<importresource="applicationContext_db.xml"/>
16</beans>


6、在com.model中创建模型类Student.java

查看源码
打印?
01package com.model;
02 
03public class Student {
04    String studentid;// 主键
05    String name;// 姓名
06    String gender;// 性别
07    String age;// 年龄
08 
09    publicString getStudentid() {
10        returnstudentid;
11    }
12 
13    publicvoid setStudentid(String studentid) {
14        this.studentid = studentid;
15    }
16 
17    publicString getName() {
18        returnname;
19    }
20 
21    publicvoid setName(String name) {
22        this.name = name;
23    }
24 
25    publicString getGender() {
26        returngender;
27    }
28 
29    publicvoid setGender(String gender) {
30        this.gender = gender;
31    }
32 
33    publicString getAge() {
34        returnage;
35    }
36 
37    publicvoid setAge(String age) {
38        this.age = age;
39    }
40 
41}


7、根据Student.java生成对应的映射文件Student.hbm.xml

查看源码
打印?
01<?xmlversion="1.0"?>
02<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
03"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
04<!-- Generated 2013-6-23 23:31:47 by Hibernate Tools 3.4.0.CR1 -->
05<hibernate-mapping>
06    <classname="com.model.Student"table="STUDENT">
07        <idname="studentid"type="java.lang.String">
08            <columnname="STUDENTID"/>
09            <generatorclass="assigned"/>
10        </id>
11        <propertyname="name"type="java.lang.String">
12            <columnname="NAME"/>
13        </property>
14        <propertyname="gender"type="java.lang.String">
15            <columnname="GENDER"/>
16        </property>
17        <propertyname="age"type="java.lang.String">
18            <columnname="AGE"/>
19        </property>
20    </class>
21</hibernate-mapping>

 

8、编写接口StudentService.java

查看源码
打印?
1package com.service;
2 
3import java.util.List;
4 
5public interface StudentService {
6     publicList getStudentList(String page,String rows) throwsException;//根据第几页获取,每页几行获取数据
7     publicint getStudentTotal() throws Exception;//统计一共有多少数据
8}


9、编写接口的实现类StudentServiceImpl.java

查看源码
打印?
01package com.serviceImpl;
02 
03import java.util.List;
04 
05import org.hibernate.SessionFactory;
06 
07import com.service.StudentService;
08 
09public class StudentServiceImpl implementsStudentService {
10    privateSessionFactory sessionFactory;
11     
12    // 根据第几页获取,每页几行获取数据
13    publicList getStudentList(String page, String rows) {
14         
15        //当为缺省值的时候进行赋值
16        intcurrentpage = Integer.parseInt((page == null|| page == "0") ?"1": page);//第几页
17        intpagesize = Integer.parseInt((rows == null|| rows == "0") ?"10": rows);//每页多少行
18         
19        List list =this.sessionFactory.getCurrentSession().createQuery("from Student")
20                       .setFirstResult((currentpage -1) * pagesize).setMaxResults(pagesize).list();
21 
22        returnlist;
23    }
24 
25    // 统计一共有多少数据
26    publicint getStudentTotal() throws Exception {
27        returnthis.sessionFactory.getCurrentSession().find("from Student").size();
28    }
29     
30    publicSessionFactory getSessionFactory() {
31        returnsessionFactory;
32    }
33 
34    publicvoid setSessionFactory(SessionFactory sessionFactory) {
35        this.sessionFactory = sessionFactory;
36    }
37     
38     
39}


10、配置连接数据库的配置文件applicationContext_db.xml

查看源码
打印?
001<?xmlversion="1.0"encoding="UTF-8"?>
002<beansxmlns="http://www.springframework.org/schema/beans"
003    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
004    xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
005    xsi:schemaLocation="http://www.springframework.org/schema/beans
006           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
007           http://www.springframework.org/schema/context
008           http://www.springframework.org/schema/context/spring-context-2.5.xsd
009           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
010           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
011 
012 
013    <!-- 用Bean定义数据源 -->
014    <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"
015        destroy-method="close">
016        <!-- 定义数据库驱动 -->
017        <propertyname="driverClass">
018            <value>oracle.jdbc.driver.OracleDriver</value>
019        </property>
020        <!-- 定义数据库URL -->
021        <propertyname="jdbcUrl">
022            <value>jdbc:oracle:thin:@localhost:1521:orcl</value>
023        </property>
024        <!-- 定义数据库的用户名 -->
025        <propertyname="user">
026            <value>lhq</value>
027        </property>
028        <!-- 定义数据库的密码 -->
029        <propertyname="password">
030            <value>lhq</value>
031        </property>
032        <propertyname="minPoolSize">
033            <value>1</value>
034        </property>
035        <propertyname="maxPoolSize">
036            <value>40</value>
037        </property>
038        <propertyname="maxIdleTime">
039            <value>1800</value>
040        </property>
041        <propertyname="acquireIncrement">
042            <value>2</value>
043        </property>
044        <propertyname="maxStatements">
045            <value>0</value>
046        </property>
047        <propertyname="initialPoolSize">
048            <value>2</value>
049        </property>
050        <propertyname="idleConnectionTestPeriod">
051            <value>1800</value>
052        </property>
053        <propertyname="acquireRetryAttempts">
054            <value>30</value>
055        </property>
056        <propertyname="breakAfterAcquireFailure">
057            <value>true</value>
058        </property>
059        <propertyname="testConnectionOnCheckout">
060            <value>false</value>
061        </property>
062 
063    </bean>
064 
065    <!--定义Hibernate的SessionFactory -->
066    <beanid="sessionFactory"
067        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
068        <!-- 定义SessionFactory必须注入dataSource -->
069        <propertyname="dataSource">
070            <refbean="dataSource"/>
071        </property>
072        <!-- 定义Hibernate的SessionFactory属性 -->
073        <propertyname="hibernateProperties">
074            <props>
075                <propkey="hibernate.dialect">
076                    org.hibernate.dialect.Oracle10gDialect
077                </prop>
078            </props>
079        </property>
080 
081        <!-- 定义POJO的映射文件 -->
082        <propertyname="mappingResources">
083            <list>
084                <value>com/model/Student.hbm.xml</value>
085            </list>
086        </property>
087    </bean>
088 
089    <!-- 配置事务拦截器 -->
090    <beanid="transactionManager"
091        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
092        <propertyname="sessionFactory"ref="sessionFactory"/>
093    </bean>
094 
095    <tx:adviceid="txAdvice"transaction-manager="transactionManager">
096        <tx:attributes>
097            <tx:methodname="save*"propagation="REQUIRED"/><!-- 只有一save、delete、update开头的方法才能执行增删改操作 -->
098            <tx:methodname="delete*"propagation="REQUIRED"/>
099            <tx:methodname="update*"propagation="REQUIRED"/>
100            <tx:methodname="*"propagation="SUPPORTS"read-only="true"/><!-- 其他方法为只读方法 -->
101        </tx:attributes>
102    </tx:advice>
103 
104    <aop:config>
105        <aop:pointcutid="interceptorPointCuts" expression="execution(* com.serviceImpl..*.*(..))"/>  <!-- 对应实现类接口的包的位置 -->
106        <aop:advisoradvice-ref="txAdvice"pointcut-ref="interceptorPointCuts"/>
107    </aop:config>
108 
109</beans>


11、在控制层编写StudentAction.java类型

查看源码
打印?
01package com.action;
02 
03import java.util.List;
04 
05import javax.servlet.http.HttpServletRequest;
06import javax.servlet.http.HttpServletResponse;
07 
08import net.sf.json.JSONObject;
09 
10import org.apache.log4j.Logger;
11import org.apache.struts2.ServletActionContext;
12 
13import com.service.StudentService;
14 
15public class StudentAction {
16    staticLogger log = Logger.getLogger(StudentAction.class);
17    privateJSONObject jsonObj;
18    privateString rows;// 每页显示的记录数
19    privateString page;// 当前第几页
20    privateStudentService student_services;//String依赖注入
21     
22    //查询出所有学生信息
23    publicString getAllStudent() throwsException {
24        log.info("查询出所有学生信息");     
25         
26        List list = student_services.getStudentList(page, rows);
27        this.toBeJson(list,student_services.getStudentTotal());
28 
29        returnnull;
30    }
31     
32    //转化为Json格式
33       publicvoid toBeJson(List list,inttotal) throws Exception{
34            HttpServletResponse response = ServletActionContext.getResponse();
35            HttpServletRequest request = ServletActionContext.getRequest();
36             
37            JSONObject jobj =new JSONObject();//new一个JSON
38            jobj.accumulate("total",total );//total代表一共有多少数据
39            jobj.accumulate("rows", list);//row是代表显示的页的数据
40 
41            response.setCharacterEncoding("utf-8");//指定为utf-8
42            response.getWriter().write(jobj.toString());//转化为JSOn格式
43             
44            log.info(jobj.toString());
45       }
46        
47 
48    publicStudentService getStudent_services() {
49        returnstudent_services;
50    }
51 
52    publicvoid setStudent_services(StudentService student_services) {
53        this.student_services = student_services;
54    }
55 
56    publicvoid setJsonObj(JSONObject jsonObj) {
57        this.jsonObj = jsonObj;
58    }
59 
60    publicvoid setRows(String rows) {
61        this.rows = rows;
62    }
63 
64    publicvoid setPage(String page) {
65        this.page = page;
66    }
67        
68        
69     
70}


12、编写Spring的依赖注入applicationContext_bean.xml配置文件

查看源码
打印?
01<?xmlversion="1.0"encoding="UTF-8"?>
02<beansxmlns="http://www.springframework.org/schema/beans"
03    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
04    xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
05    xsi:schemaLocation="http://www.springframework.org/schema/beans
06           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
07           http://www.springframework.org/schema/context
08           http://www.springframework.org/schema/context/spring-context-2.5.xsd
09           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
10           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
11     
12    <!-- 业务层Service -->
13    <beanid="student_service"class="com.serviceImpl.StudentServiceImpl">
14        <propertyname="sessionFactory">
15             <refbean="sessionFactory"></ref>
16        </property>
17    </bean>
18 
19    <!-- 控制层Action -->
20    <beanid="student_action"class="com.action.StudentAction">
21        <propertyname="student_services">
22             <refbean="student_service"/>
23        </property>
24    </bean>
25     
26</beans>


13、编写struts.xml配置文件

查看源码
打印?
01<?xmlversion="1.0"encoding="UTF-8"?>
02<!DOCTYPE struts PUBLIC
03"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
04"http://struts.apache.org/dtds/struts-2.0.dtd">
05<struts>
06    <packagename="Easyui"extends="json-default">
07        <!-- 学生信息 -->
08        <actionname="getAllStudentAction"class="student_action"method="getAllStudent">
09            <resulttype="json"> </result>
10        </action>
11    </package>
12</struts>


14、编写JSP----index.jsp

查看源码
打印?
01<%@ page language="java" pageEncoding="utf-8" isELIgnored="false"%>
02<%
03    String path = request.getContextPath();
04%>
05<%@ taglib prefix="s" uri="/struts-tags"%>
06<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
07<html>
08<head>
09<metahttp-equiv="Content-Type"content="text/html; charset=utf-8">
10<title>数字框</title>
11<!-- 引入Jquery -->
12<scripttype="text/javascript"  src="<%=path%>/js/easyui/jquery-1.8.0.min.js" charset="utf-8"></script>
13<!-- 引入Jquery_easyui -->
14<scripttype="text/javascript"  src="<%=path%>/js/easyui/jquery.easyui.min.js" charset="utf-8"></script>
15<!-- 引入easyUi国际化--中文 -->
16<scripttype="text/javascript"  src="<%=path%>/js/easyui/locale/easyui-lang-zh_CN.js" charset="utf-8"></script>
17<!-- 引入easyUi默认的CSS格式--蓝色 -->
18<linkrel="stylesheet"type="text/css"  href="<%=path%>/js/easyui/themes/default/easyui.css" />
19<!-- 引入easyUi小图标 -->
20<linkrel="stylesheet"type="text/css"  href="<%=path%>/js/easyui/themes/icon.css" />
21 
22<scripttype="text/javascript">
23    $(function() {
24        $('#mydatagrid').datagrid({
25            title : 'datagrid实例',
26            iconCls : 'icon-ok',
27            width : 600,
28            pageSize : 5,//默认选择的分页是每页5行数据
29            pageList : [ 5, 10, 15, 20 ],//可以选择的分页集合
30            nowrap : true,//设置为true,当数据长度超出列宽时将会自动截取
31            striped : true,//设置为true将交替显示行背景。
32            collapsible : true,//显示可折叠按钮
33            toolbar:"#tb",//在添加 增添、删除、修改操作的按钮要用到这个
34            url:'getAllStudentAction.action',//url调用Action方法
35            loadMsg : '数据装载中......',
36            singleSelect:true,//为true时只能选择单行
37            fitColumns:true,//允许表格自动缩放,以适应父容器
38            //sortName : 'xh',//当数据表格初始化时以哪一列来排序
39            //sortOrder : 'desc',//定义排序顺序,可以是'asc'或者'desc'(正序或者倒序)。
40            remoteSort : false,
41             frozenColumns : [ [ {
42                field : 'ck',
43                checkbox : true
44            } ] ],
45            pagination : true,//分页
46            rownumbers : true//行数
47        });
48         
49    });
50     
51</script>
52 
53</head>
54<body>
55    <h2>
56        <b>easyui的DataGrid实例</b>
57    </h2>
58 
59    <tableid="mydatagrid">
60       <thead>
61            <tr>
62                <thdata-options="field:'studentid',width:100,align:'center'">学生学号</th>
63                <thdata-options="field:'name',width:100,align:'center'">姓名</th>
64                <thdata-options="field:'gender',width:100,align:'center'">性别</th>
65                <thdata-options="field:'age',width:100,align:'center'">年龄</th>
66            </tr>
67        </thead>
68    </table>
69    
70</body>
71</html>


15、启动程序,输入http://localhost:8080/easyui/index.jsp进行测试

 

来自:http://blog.csdn.net/lhq13400526230/article/details/9158111
 

0 0
原创粉丝点击