J'ai récemment appris Easyi et j'ai trouvé que c'était très utile et l'interface est magnifique. Notez votre expérience d'apprentissage ici. Ce blog écrit SSH et Easyi pour implémenter l'affichage de pagination de DataGrid. D'autres fonctions telles que l'ajout, la modification, la suppression, la suppression par lots, etc. seront écrites une par une plus tard.
Tout d'abord, jetons un coup d'œil à l'effet pour réaliser: lorsque 5 lignes de données sont affichées par page:
Lorsque 10 lignes de données sont affichées par page, l'effet est le suivant:
Étapes spécifiques:
1. Téléchargez Easyi et construisez un environnement.
2. Construire un projet SSH, et la structure du répertoire de l'ensemble du projet est présentée sur la figure:
3. Créez un étudiant de table dans la base de données Oracle. Et entrez les 6 lignes de données suivantes. Étant donné que l'opération d'addition n'a pas encore été implémentée, ajoutez d'abord des données à la table de base de données. La valeur par défaut est de 5 données par ligne, veuillez donc entrer au moins 6 lignes de données pour faciliter les tests de pagination.
4. Configuration Web.xml
<? 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-Class> org.apache.struts2.dispatcher.ng.filter.strutsprepareandexEcuteFilter </filter-Class> </filter> <filter-mapping> <filter-name> Struts2 </ Filter-Name> <UrL-Pattern> / * </url-Pattern> </filter-Maping> <ousiner-Class> org.springframework.web.context.contextloadherListener </ écouteur-class> </diner> <! - Positionnement de l'emplacement physique de l'applicationContext.xml -> <Fouxet-Param> <Am param-name> ContextConfiglocation </ param-name> <param-value> classpath: applicationContext.xmlor </ context-param> </ web-app>
5. Configuration de 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.springframeworkwork.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-20 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 ressource = "ApplicationContext_Bean.xml" /> <Importer Resource = "ApplicationContext_db.xml" /> </EANS>
6. Créer la classe Model Class Student.java dans com.model
package com.model; classe publique Student {String StudentID; // Nom de chaîne de clé primaire; // Nom String Sexe; // Gender String Age; // Age public String getStudentid () {return StudentId; } public void SetStudentid (String StudentID) {this.Studentid = StudentId; } public String getName () {Nom de retour; } public void setName (string name) {this.name = name; } public String getgender () {return Gender; } public void setGender (String Sexe) {this.gender = genre; } public String Getage () {return Age; } public void Setage (String Age) {this.age = age; }} 7. Générer le fichier de mappage correspondant Student.hbm.xml selon 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"> <! -> <hibernate-mapping> <class name = "com.model.student" table = "student"> <id name = "StudentId" type = "java.lang.string"> <colonnel name = "StudentID" /> <générateur /> </ id> <propriété name = "name" type = "java.lang.string"> <colonne type = "java.lang.string"> <colonnel name = "Gender" /> </ propriété> <propriété name = "age" type = "java.lang.string"> <colonnel name = "Age" /> </ propriété> </ class> </ hibernate-mapping>
8. Écrivez l'interface StudentService.java
package com.service; importer java.util.list; public interface StudentService {public list getStudentList (page de chaîne, lignes de chaîne) lève une exception; // récupérer les données en fonction de la page, et obtenir des données de chaque page public int getStudentTotal () lève une exception; // statistiques combien de données y a-t-il au total} 9. Écrivez la classe Implémentation de l'interface StudentServiceImpl.java
Package Com.ServiceIMPl; import java.util.list; import org.hibernate.SessionFactory; import com.service.studentsService; public class studentserviceIMPl implémente StudentService {private Session SessionFactory; // récupérer les données en fonction de la page et obtenir des données pour plusieurs lignes par page Liste publique GetStudentList (page de chaîne, lignes de chaîne) {// Attribuer une valeur lorsque c'est la valeur par défaut int CurrentPage = Integer.Parseint ((page == null || page == "0")? "1": page); // ? Liste de retour; } // Statistiques La quantité de données y a-t-il dans le public total int getStudentTotal () lève une exception {return this.sessionfactory.getCurrentession (). Find ("from étudiant"). Size (); } public SessionFactory getSessionFactory () {return SessionFactory; } public void setSessionFactory (SessionFactory SessionFactory) {this.SessionFactory = SessionFactory; }} 10. Configurez le fichier de configuration pour se connecter à la base de données 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.springframeworkwork.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-20 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 " bean -> <bean id = "dataSource" destrie-méthod = "close"> <! - Définition du pilote de base de données -> <propriété name = "DriverClass"> <value> oracle.jdbc.driver.oracledriver </value> </ propriété> <! - Définition de la base de données url -> <propriété name = "jdbcurl"> <value> jdbc: oracle: mince: @localhost: 1521: orcl </value> </ propriété> <! - Définissez le nom d'utilisateur de la base de données -> <propriété name = "user"> <value> lhq </value> </ propriété> <! - Définissez le mot de passe de la base de données -> <propriété Name = "Passway"> <Value> Lhq </value> name = "MinpoolSize"> <value> 1 </value> </ propriété> <propriété name = "maxpoolSize"> <value> 40 </ value> </ propriété> <propriété name = "maxidleTime"> <value> 1800 </value> </ propriété <propriété name = "AcquireIncrement"> <value> 2 </value> </près> <propriété Name = "MaxStatations"> <value> </value> </près> <Valeur </ propriété> <propriété name = "initialPoolSize"> <value> 2 </ value> </ propriété> <propriété name = "idleconnectiontestperiod"> <value> 1800 </value> </ propriété> <propriété name = "acquerreetAtAmpts"> <value> 30 <value> </premyweple </ property> </ property> </ property> </ property> name = "TestConnectionOnCheckout"> <value> false </value> </ propriété> </ bean> <! - Définir Hibernate SessionFactory -> <bean id = "SessionFactory"> <! - Définir SessionFactory doit être injecté dans DataSource -> <propriété Name = "DataSource"> <Refacturn PropertyFact -> <propriété name = "HiberNateProperties"> <props> <prop key = "hibernate.dialect"> org.hibernate.dialect.oracle10gdialect </prop> </props> </ propriété> <! - Définissez le fichier de mappage pour Pojo -> <propriété Name = "MappingResources"> <Sist <value> com / model / student.hbm.xml </value> </sist> </ propriété> </ bean> <! - Configurer les transactions interceptor -> <bean id = "TransactionManager"> <propriété name = "sessionfactory" ref = "SessionFactory" /> </ bean> <tx: conseils id = "txadvice" transaction-manager = "TransactionManAr"> <tx: <tx> <tx> transaction-manager = "TransactionManAn name = "Save *" propagation = "requise" /> <! - Seules les méthodes commençant par enregistrer, supprimer et mettre à jour peuvent être effectuées -> <tx: méthode name = "delete *" propagation = "requise" /> <tx: méthode name = "update *" propagation = "requise" /> <tx: méthode name = "*" propegation = "supports" readly = "true" /> <! </ tx: attributs> </ tx: conseils> <aop: config> <aop: Pointcut id = "interceptorpointcuts" expression = "EXECUTION (* com.serviceImpl .. *. * (..))" /> <! - l'emplacement du pack /> </ aop: config> </ beans>
11. Écrivez StudentAction.java Type dans la couche de contrôle
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.strutts2.s.ServletACTCONT com.service.StudentsService; public class StudentAction {static logger log = logger.getLogger (studentAction.class); JsonObject JsonOBJ privé; lignes de chaînes privées; // nombre d'enregistrements affichés sur chaque page Page Private String Page; // Quelle page est la StudentService StudentS de Student_Services actuelle; // Injection de dépendance de chaîne // Requête toutes les informations de l'étudiant public String GetAllStudent () lève une exception {log.info ("requérir toutes les informations étudiantes"); List list = Student_Services.getStudentList (page, lignes); this.tobejson (liste, étudiant_services.getStudentTotal ()); retourner null; } // Converti au format JSON public void tabejson (liste de liste, int total) lève une exception {httpServletResponse réponse = servletActionContext.getResponse (); HttpServLetRequest request = servletActionContext.getRequest (); JSONOBject Jobj = new JSONObject (); // new a json json json json json json json json Response.getWriter (). WRITE (JobJ.ToString ()); // Converti au format JSON 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 (Page de chaîne) {this.page = page; }} 12. Écrivez l'injection de dépendance de Spring ApplicationContext_Bean.xml Fichier de configuration
<? 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.springframeworkwork.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-20 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 "> <! - <bean id = "Student_Service"> <propriété name = "SessionFactory"> <ref bean = "SessionFactory"> </ Ref> </ Property> </ Bean> <! - Controly Layer Action -> <Bean Id = "Student_action"> <propriété Name = "Student_Service"> <Ref Bean = "Student_Service" /> </ Property> </EAND> </EANTS>
13. Écrivez le fichier de configuration de strut.xml
<? 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"> <stress> <package nom = "EasyUi" étend = "jon"> <! Informations sur l'étudiant -> <action name = "getAllStudentAction" méthode = "getAllStudent"> <Result Type = "JSON"> </ result> </ action> </macking> </truts>
14. Écrire 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 HTML 4.01 Transitional / En" "http://www.w3.org/tr/html4/loose.dtd"><html><head><meta http-equiv =" contenu-type "contenu =" Text / html; charset = utf-8 "> <Title> Number Box </ Title> <! - Introduction jquery -> <Script Type =" src = "<% = path%> / js / easyui / jquery-1.8.0.min.js" charset = "utf-8"> </ script> <! - introduisant jQuery_easyui -> <script type = "text / javascript" src = "<% = path%> / js / easyui.easyui.Min.js" charset = "utf-8"> </ script> <! - introduisant jQuery_easyui -> <script type = "text / javascript" src = "<% = path%> / js / easyui / jQuery.easyui.min.js" Charset = "utf-8"> </ script> <! - introduire easyui international - chinois -> <script> <! src = "<% = path%> / js / easyui / locale / easyui-lang-zh_cn.js" charset = "utf-8"> </ script> <! - introduire le format css easyui par défaut -> <link rel = "Stylesheet" type = "text / css" href = "<% = path%> / js / easyui / themes / default / easyui.css" /> <! - introduire easyui small icon -> <link rel = "Stylesheet" type = "text / css" href = "<% = path%> / js / easyui / themes / icon.css" /> <script type = "text / javascript"> $ () ")" $ ('# mydatagrid'). datagrid ({title: 'datagrid instance', iconcls: 'icon-ok', width: 600, pagesize: 5, // la page sélectionnée par défaut est 5 lignes de données par page pageList: [5, 10, 15, 20], // le jeu de pagin arrière-plan. Bollable: true, // Afficher la barre d'outils de bouton pliable: "# TB", // Ceci doit être utilisé lors de l'ajout, de la suppression et de la modification des boutons URL: 'GetAllStudentAction.Action', // Url appelle la méthode d'action Loadmsg: 'Data Loading:' ' // sortName: 'xh', // Quelle colonne est utilisée pour trier lorsque la table de données est initialisée // SortOrder: 'DESC', // Définissez l'ordre de tri, qui peut être 'ASC' ou 'DESC' (ordre positif ou inversé). Remotesort: false, Frozencolumns: [[{champ: 'ck', cocher box: true}]], pagination: true, // pagination RownUmbers: true // numéro de ligne}); }); </ script> </ head> <body> <h2> <b> Instance de données d'acide </b> </h2> <table id = "MyDataGrid"> <Thead> <tr> <th Data-Options = "Field: 'StudentId', Width: 100, Align: 'Center'"> Numéro d'étudiant </th> < Data-Options = "Field: 'Name', Width: 100, Align: 'Center'"> Name </ Th> <th Data-Options = "Field: 'Gender', Width: 100, Align: 'Center'"> Sex </ Th> <TH Data-Options = "Field: 'Age', Width: 100, Align: 'Center' '"> Age </ Th> </r> </ body> </html>15. Démarrez le programme et entrez http: // localhost: 8080 / easyui / index.jsp pour les tests.
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.