Я недавно выучил Easy и обнаружил, что он очень полезен, а интерфейс красивый. Запишите свой опыт обучения здесь. Этот блог пишет SSH и Easyi, чтобы реализовать отображение пагивации DataGrid. Другие функции, такие как добавление, модификация, удаление, удаление партии и т. Д., Будут записаны один за другим.
Во -первых, давайте посмотрим на эффект для достижения: когда 5 строк данных отображаются на страницу:
Когда 10 строк данных отображаются на страницу, эффект заключается в следующем:
Конкретные шаги:
1. Скачайте Easy и создайте среду.
2. Создайте проект SSH, и структура каталогов всего проекта показана на рисунке:
3. Создание студента таблицы в базе данных Oracle. И введите следующие 6 рядов данных. Поскольку операция добавления еще не была реализована, сначала добавьте данные в таблицу базы данных. Значение по умолчанию составляет 5 данных на строку, поэтому, пожалуйста, введите не менее 6 строк данных, чтобы облегчить тестирование под падением.
4. Конфигурация web.xml
<? xml version = "1.0" Encoding = "utf-8"?> <web-app arser = "2,5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/xmlschema electan "/www.w3. xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-Filter-sttus2-> <Filter> <FilterTer> StruTS2 </! <filter-class> org.apache.struts2.dispatcher.ng.filter.strutspreareAndexecutefilter </filter-class> </filter> <Filter-mapping> <Filter-name> Struts2 </filter-name> <url-pattern>/*</url-pattern> </filter-name> <url-pattern>/*</url-pattern> </filter> <!->/*</url-pattern> <! <lloader-class> org.springframework.web.context.contextloaderListener </sluster> </alinger> <!-Позиционирование физического местоположения ApplicationContext.xml-> <cestempt-param> <param-name> contextConfiglocation </param-ame> <param-value> classpath: apportive.xml <//param-name> <param-value> classpath: apportive.xml <//context-parampate> </param-valam
5. Конфигурация 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.springframe.orshema. xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.spramework.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.xspormportwork.org/schema/tx/spring--2.5. resource = "ApplicationContext_bean.xml"/> <import resource = "ApplicationContext_db.xml"/> </beans>
6. Создайте Model Class Student.java в com.model
пакет com.model; public Class Student {string StudentId; // Имя основного ключа; // имя строки 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 (строка пол) {this.gender = gender; } public String getAge () {return Age; } public void setage (String Age) {this.age = age; }} 7. Сгенерируйте соответствующий файл сопоставления Student.hbm.xml в соответствии с 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"> <!-сгенерировано 2013-6-23 23:31:47. -> <Hibernate Mapping> <class name = "com.model.student" table = "Student"> <id name = "student" type = "java.lang.string"> <column name = "Student" /> <Generator /> < /id> <property name = "name" type = "java.lang.string"> < /id name "> < /name" name "java.lang.string"> < /name "> < /> < /name" " /" name "> < /> < /> < /> < /> < /> < /> < /> < /> < /name" = "" /"" /"" /"" /"" /".". type = "java.lang.string"> <column name = "gender"/> </property> <name = "age" type = "java.lang.string"> <name = "age"/> </propetion> </class> </hibernate mapping>
8. Напишите интерфейс Student Sensers.java
Пакет com.service; import java.util.list; public interface undious undervice {public list getStudentList (String Page, String Rows) Throws Exception; // Извлекать данные в соответствии со страницей и получить данные с каждой страницы public int getStudentTotal (), выбрасывает исключения; // Статистические данные. Каковы данные. 9. Напишите класс внедрения интерфейса.
пакет com.serviceimpl; import java.util.list; import org.hibernate.sessionFactory; import com.service.studentservice; общественный класс Counderserviceimpl реализует студенческий сервис {private SessionFactory SessionFactory; // Извлекать данные в соответствии со страницей и получить данные для нескольких строк на страницу общедоступного списка GetStudentList (String Page, String Rows) {// Присвоение значения, когда это значение по умолчанию int currentPage = integer.parseint ((page == null || page == "0")? «0»)? вернуть список; } // СТАТИСТИКА Сколько данных в общем public int getStudentTotal () выбрасывает исключение {return this.sessionFactory.getCurrentSession (). Найти ("от студента"). Size (); } public sessionFactory getSessionFactory () {return SessionFactory; } public void setSessionFactory (sessionFactory SessionFactory) {this.SessionFactory = sessionFactory; }} 10. Настройте файл конфигурации для подключения к базе данных 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.springframe.orshema. xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.spramework.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. Bean-> <bean id = "dataSource" Dressome-method = "close"> <!-Определение драйвера базы данных-> <name = "driverclass"> <dalue> oracle.jdbc.driver.oracledriver </value> </propetion> <!-Определение URL базы данных-> <свойство = "Jdbcurl> <! <dulch> jdbc: Oracle: thin: @localhost: 1521: orcl </value> </property> <!-Определите имя пользователя базы данных-> <name = "user"> <datue> lhq </value> </propetory> <!-Определите пароль базы данных-> <proport = "> <duld> lhq </! name = "minpoolsize"> <dalue> 1 </value> </property> <name = "maxpoolsize"> <dalue> 40 </value> </property> <name = "maxidletime"> <dulch> 1800 </value> </property> <name = "affireIncrement"> <dute> 2 </value> </propertive> <property name = "maxStations"/value> </value> </propertive> <property> </value> </valure> </propertive> <property> " </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"> <dall> false </value> </property> </bean> <!-определить Hibernate SessionFactory-> <Bean Id = "SessionFactory"> <!-Define SessionFactory должен быть введен в DataSource-> <Property name = "DataSource"> <Ref Bean = "DataSource"/> <//"-свойство? <Property name = "hibernateProperties"> <props> <prop key = "hibernate.dialect"> org.hibernate.dialect.oracle10gdialect </prop> </props> </property> <!-Define Mapping File для pojo-> <proport name = "mappingResourcess"> <silect> <dulity> <dulity> com/stocday/stocday.h. </list> </property> </bean> <!-Configure Transaction Interceptor-> <bean id = "transactionManager"> <name = "sessionFactory" ref = "sessionFactory"/> </bean> <tx: usd id = "txAdvice" transaction-manager = "transactionManager"> <tx: attributes> <tx: method nemage = "save"/"save"/"save"/"save"/"save"/"save"/"save"! Можно выполнить только методы, начинающиеся с сохранения, удаления и обновления-> <tx: method name = "delete*" opragation = "требуется" /> <tx: method name = "update*" Propagation = "требуется" /> <tx: имя метода = "*" Propagation = "Поддерживает" read-nely = "true" /> <!-Другие методы чтения являются методами чтения:> < / /tx:> < /> <! <aop: config> <aop: pointcut id = "receptorpointcuts" Expression = "выполнение (*com.serviceimpl ..*.*(..))" /> <!-местоположение пакета, который реализует интерфейс класса-> <aop: Advisor Asse-ref = "txadvice" pointcut-ref = "upperportcutcuts> < / /aopers> < / /aopems> < / /aopers> < / /aops> < / /aops> < / /aops> < / /ref =" /aopects> < / /aopef
11. Напишите StudentAction.java Тип в контрольном слое
пакет com.action; import java.util.list; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; импорт net.sf.json.jsonobject; импорт org.apache.log4j.logger; com.service.studentservice; public Class StudentAction {static logger log = logger.getLogger (studentAction.class); Частный jsonObject jsonObj; Private String Rows; // Количество записей, отображаемых на каждой странице Private String Page; // Какая страница является текущей частной студенческой службой Student_services; // string -зависимость инъекция // Запросить всю информацию о студентах public String getAllStudent () Throws Exception {log.info («Запрос всех студентов информации»); Список списка = Student_services.getStudentList (Page, Rows); this.tobejson (list, student_services.getstudenttotal ()); вернуть ноль; } // конвертировать в формат json public void tobejson (список, int total) throws exection {httpservletresponse response = servletactionContext.getResponse (); Httpservletrequest request = servletactioncontext.getRequest (); JsonObject jobj = new jsonObject (); // new a json jobj.accumulate («total», total); // Общее количество представляет, сколько данных в общей сложности («Rows», List); // row-это данные, представляющие отображаемую страницу. response.getWriter (). write (jobj.toString ()); // конвертировать в формат json log.info (jobj.toString ()); } public StudentService getStudent_Services () {return Student_services; } public void setStudent_services (Studentervice Student_services) {this.student_services = Student_services; } public void setjsonObj (jsonObject jsonObj) {this.jsonobj = jsonobj; } public void setRows (String Rows) {this.rows = row; } public void set -setPage (String Page) {this.page = page; }} 12. Напишите файл конфигурации Spring Spring.
<? 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.springframe.orshema. xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.spramework.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. <bean id = "Student_service"> <name = "sessionFactory"> <ref bean = "sessionFactory"> </ref> </property> </bean> <!-Действие по контролю-> <bean Id = "student_action"> <proport name = "Student_service"> <Ref Bean = "student_service"/> </property> </bean> </beanse "
13. Написать файл конфигурации struts.xml
<? xml version = "1.0" Encoding = "UTF-8"?> <! Doctype Struts Public "-// Apache Software Foundation // Конфигурация Struts DTD 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <nace = "easy" easku "easei" exemu "easei" easku "easku"! Информация о студенте-> <name = "getAllStudentAction" method = "getAllStudent"> <result type = "json"> </result> </action> </package> </struts>
14. Напишите jsp ---- index.jsp
<%@ page language = "java" pageencoding = "utf-8" iselignored = "false"%> <%string path = request.getContextPath ();%> <%@ prefix@ taglib = "s" uri = "/struts-tags"%> <! doctpe html public "// w3c // dtd html html/en en en en en en en en en en en en en en en en en en en en en en n. «http://www.w3.org/tr/html4/loose.dtd"><html><head><meta http-equiv =" content-type "content =" text/html; charset = utf-8 "> javisc number </title> <! src = "<%= path%>/js/easyui/jquery-1.8.0.min.js" charset = "utf-8"> </script> <!-Введение jquery_easyui-> <script type = "text/javascript" src = "<%= path%>/js/useui/jquery.easy. charset = "utf-8"> </script> <!-Представляем jquery_easyui-> <script type = "text/javascript" src = "<%= path%>/js/easyui/jquery.easyui.min.js" charset = "utf-8"> </script> <! type = "text/javascript" src = "<%= path%>/js/easyui/locale/easyui-lang-zh_cn.js" charset = "utf-8"> </script> <!-Введение в формат CSS по умолчанию. href = "<%= path%>/js/easyui/themes/default/easyui.css"/> <!-ввести легкий значок easyU { $('#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 автоматически отображать фон строки. COPLASBIL: TRUE, // Показать панель инструментов складной кнопки: «#TB», // Это следует использовать при добавлении, удалении и изменении кнопок URL // sortName: 'xh', // Какой столбец используется для сортировки при инициализировании таблицы данных // sortorder: 'desc', // определить порядок сортировки, который может быть «ASC» или «desc» (положительный или обратный порядок). remoteSort: false, frozencolumns: [[{Field: 'ck', флажок: true}]], страница: true, // pagination rownumbers: true // номер строки}); }); </script> </head> <body> <h2> <b> экземпляр DataGrid of eSyi </b> </h2> <table id = "myDataGrid"> <TheAd> <tr> <th Data-options = "Field: 'Student', ширина: 100, выравнивание: 'center'> № студента </th> <th hold data-options = "Field: 'name', ширина: 100, выравнивание: 'center'"> name </th> <th Data-options = "Field:« Пол ', ширина: 100, выравнивание:' Center '"> Пол </th> <th Data-Options =" Field:' Age ', ширина: 100, Align:' Center '> Age </th> </tr> </tr> </tread> </tr> </tread> </tr> </tread> </tr> </tread> </tr> </tread> </tr> </tr> </tread> </tr> </body> </html>15. Запустите программу и введите http: // localhost: 8080/easyui/index.jsp для тестирования.
Вышеуказанное - все содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.