I recently learned Easyi and found it is very useful and the interface is beautiful. Write down your learning experience here. This blog writes SSh and Easyi to implement the pagination display of Datagrid. Other functions such as adding, modifying, deleting, batch deleting, etc. will be written one by one later.
First, let’s take a look at the effect to achieve: When 5 lines of data are displayed per page:
When 10 lines of data are displayed per page, the effect is as follows:
Specific steps:
1. Download Easyi and build an environment.
2. Build an SSH project, and the directory structure of the entire project is shown in the figure:
3. Create table Student in Oracle database. And enter the following 6 rows of data. Since the addition operation has not been implemented yet, add data to the database table first. The default value is 5 data per line, so please enter at least 6 lines of data to facilitate paging testing.
4. Web.xml configuration
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Sttus2 filter--> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Listener Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Positioning the physical location of applicationContext.xml --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param></web-app>
5. Configuration of applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><import resource="applicationContext_bean.xml"/><import resource="applicationContext_db.xml"/></beans>
6. Create the model class Student.Java in com.model
package com.model;public class Student { String studentid;// Primary key String name;// Name String gender;// Gender String age;// Age public String getStudentid() { return studentid; } public void setStudentid(String studentid) { this.studentid = studentid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }} 7. Generate the corresponding mapping file Student.hbm.xml according to Student.java
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated 2013-6-23 23:31:47 by Hibernate Tools 3.4.0.CR1 --><hibernate-mapping> <class name="com.model.Student" table="STUDENT"> <id name="studentid" type="java.lang.String"> <column name="STUDENTID" /> <generator /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="gender" type="java.lang.String"> <column name="GENDER" /> </property> <property name="age" type="java.lang.String"> <column name="AGE" /> </property> </class></hibernate-mapping>
8. Write interface StudentService.java
package com.service;import java.util.List;public interface StudentService { public List getStudentList(String page,String rows) throws Exception;//Fetch data according to the page, and get data from each page public int getStudentTotal() throws Exception;//Statistics how much data is there in total} 9. Write the interface implementation class StudentServiceImpl.java
package com.serviceImpl;import java.util.List;import org.hibernate.SessionFactory;import com.service.StudentService;public class StudentServiceImpl implements StudentService { private SessionFactory sessionFactory; //Fetch data according to the page, and obtain data for several rows per page public List getStudentList(String page, String rows) { // Assign value when it is the default value int currentpage = Integer.parseInt((page == null || page == "0") ? "1": page);//How many pages int pagesize = Integer.parseInt((rows == null || rows == "0") ? "10": rows);//How many rows per page List = this.sessionFactory.getCurrentSession().createQuery("from Student") .setFirstResult((currentpage - 1) * pagesize).setMaxResults(pagesize).list(); return list; } // Statistics how much data is there in total public int getStudentTotal() throws Exception { return this.sessionFactory.getCurrentSession().find("from Student").size(); } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } } 10. Configure the configuration file for connecting to the database applicationContext_db.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- Defining the data source with bean--> <bean id="dataSource" destroy-method="close"> <!-- Defining the database driver--> <property name="driverClass"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <!-- Defining the database URL --> <property name="jdbcUrl"> <value>jdbc:oracle:thin:@localhost:1521:orcl</value> </property> <!-- Define the user name of the database --> <property name="user"> <value>lhq</value> </property> <!-- Define the password of the database --> <property name="password"> <value>lhq</value> </property> <property name="minPoolSize"> <value>1</value> </property> <property name="maxPoolSize"> <value>40</value> </property> <property name="maxIdleTime"> <value>1800</value> </property> <property name="acquireIncrement"> <value>2</value> </property> <property name="maxStatements"> <value>0</value> </property> <property name="initialPoolSize"> <value>2</value> </property> <property name="idleConnectionTestPeriod"> <value>1800</value> </property> <property name="acquireRetryAttempts"> <value>30</value> </property> <property name="breakAfterAcquireFailure"> <value>true</value> </property> <property name="testConnectionOnCheckout"> <value>false</value> </property> </bean> <!--Define Hibernate SessionFactory --> <bean id="sessionFactory"> <!-- Define SessionFactory must be injected into dataSource --> <property name="dataSource"> <ref bean="dataSource" /> </property> <!-- Define Hibernate SessionFactory property --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.Oracle10gDialect </prop> </props> </property> <!-- Define the mapping file for POJO--> <property name="mappingResources"> <list> <value>com/model/Student.hbm.xml</value> </list> </property> </bean> <!-- Configure transaction interceptor--> <bean id="transactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /><!-- Only methods starting with save, delete, and update can be performed--> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="*" propagation="SUPPORTS" read-only="true" /><!-- Other methods are read-only methods--> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="interceptorPointCuts" expression="execution(* com.serviceImpl..*.*(..))" /> <!-- The location of the package that implements the class interface--> <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" /> </aop:config></beans>
11. Write StudentAction.java type in the control layer
package com.action;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;import org.apache.log4j.Logger;import org.apache.struts2.ServletActionContext;import com.service.StudentService;public class StudentAction { static Logger log = Logger.getLogger(StudentAction.class); private JSONObject jsonObj; private String rows;// Number of records displayed on each page private String page;// What page is the current private StudentService student_services;//String dependency injection//Query all student information public String getAllStudent() throws Exception { log.info("Query all student information"); List list = student_services.getStudentList(page, rows); this.toBeJson(list,student_services.getStudentTotal()); return null; } //Convert to Json format public void toBeJson(List list,int total) throws Exception{ HttpServletResponse response = ServletActionContext.getResponse(); HttpServletRequest request = ServletActionContext.getRequest(); JSONObject jobj = new JSONObject();//new a JSON jobj.accumulate("total",total );//total represents how much data there is in total jobj.accumulate("rows", list);//row is the data representing the displayed page response.setCharacterEncoding("utf-8");//Specify as utf-8 response.getWriter().write(jobj.toString());//Convert to JSOn format log.info(jobj.toString()); } public StudentService getStudent_services() { return student_services; } public void setStudent_services(StudentService student_services) { this.student_services = student_services; } public void setJsonObj(JSONObject jsonObj) { this.jsonObj = jsonObj; } public void setRows(String rows) { this.rows = rows; } public void setPage(String page) { this.page = page; } } 12. Write spring's dependency injection applicationContext_bean.xml configuration file
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- Business Layer Service --> <bean id="student_service"> <property name="sessionFactory"> <ref bean="sessionFactory"></ref> </property> </bean> <!-- Control Layer Action --> <bean id="student_action"> <property name="student_service"> <ref bean="student_service" /> </property> </bean> </beans>
13. Write struts.xml configuration file
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"><struts> <package name="Easyui" extends="json-default"> <!-- Student Information--> <action name="getAllStudentAction" method="getAllStudent"> <result type="json"> </result> </action> </package></struts>
14. Write JSP----index.jsp
<%@ page language="java" pageEncoding="utf-8" isELIgnored="false"%><% String path = request.getContextPath();%><%@ taglib prefix="s" uri="/struts-tags"%><!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>Number box</title><!-- Introducing Jquery --><script type="text/javascript" src="<%=path%>/js/easyui/jquery-1.8.0.min.js" charset="utf-8"></script><!-- Introducing Jquery_easyui --><script type="text/javascript" src="<%=path%>/js/easyui/jquery.easyui.min.js" charset="utf-8"></script><!-- Introducing Jquery_easyui --><script type="text/javascript" src="<%=path%>/js/easyui/jquery.easyui.min.js" charset="utf-8"></script><!-- Introduce easyUi internationalization--Chinese--><script type="text/javascript" src="<%=path%>/js/easyui/locale/easyui-lang-zh_CN.js" charset="utf-8"></script><!-- Introduce easyUi default CSS format--blue--><link rel="stylesheet" type="text/css" href="<%=path%>/js/easyui/themes/default/easyui.css" /><!-- Introduce easyUi small icon--><link rel="stylesheet" type="text/css" href="<%=path%>/js/easyui/themes/icon.css" /><script type="text/javascript"> $(function() { $('#mydatagrid').datagrid({ title : 'datagrid instance', iconCls : 'icon-ok', width : 600, pageSize : 5,//The default selected page is 5 rows of data per page pageList : [ 5, 10, 15, 20 ],//The paging set that can be selected nowrap : true,//Set to true, striped : true,//Set to true will automatically display the row background. collapsible : true,//Show foldable button toolbar:"#tb",//This should be used when adding, deleting, and modifying buttons url:'getAllStudentAction.action',//url calls Action method loadMsg: 'Data loading...', singleSelect:true,// When true, you can only select a single row fitColumns:true,//Allow the table to automatically scale to suit the parent container //sortName : 'xh',//Which column is used to sort when the data table is initialized //sortOrder : 'desc',//Define the sort order, which can be 'asc' or 'desc' (positive or reverse order). remoteSort : false, frozenColumns : [ [ { field : 'ck', checkbox : true } ] ], pagination : true,//pagination rownumbers : true//line number}); }); </script> </head><body> <h2> <b> DataGrid instance of easyi</b> </h2> <table id="mydatagrid"> <thead> <tr> <th data-options="field:'studentid',width:100,align:'center'">Student number</th> <th data-options="field:'name',width:100,align:'center'">name</th> <th data-options="field:'gender',width:100,align:'center'">Gender</th> <th data-options="field:'age',width:100,align:'center'">Age</th> </tr> </tead> </table> </body></html>15. Start the program and enter http://localhost:8080/easyui/index.jsp for testing.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.