ก่อนที่จะแชร์รหัสการดำเนินการสำหรับหน้าการสืบค้นทั้งหมดให้ทำความเข้าใจกับกระบวนการดำเนินการก่อน
1. โดยทั่วไปจะใช้ mybatis plug-in interceptor เพื่อสกัดกั้นก่อนการดำเนินการ SQL และเพิ่มขีด จำกัด XX ลงในคำสั่ง Query
2. ใช้วัตถุหน้าเพื่อเรียกใช้ผ่านกระบวนการดำเนินการทั้งหมด วัตถุหน้านี้ต้องการการเขียนส่วนประกอบการแบ่งหน้าส่วนหน้าใน Java
3. ใช้ชุดสามชั้นที่ค่อนข้างสมบูรณ์ DAO และบริการเพื่อสนับสนุนสถาปัตยกรรมการปนเปื้อนนี้
4. คลาสเสริมบางคลาสที่ใช้ในหน้านี้
หมายเหตุ: มีการแชร์เนื้อหาจำนวนมาก ฉันจะไม่แสดงรายการขวดที่ต้องการทีละหนึ่ง เมื่อคุณใช้ฟังก์ชั่นการปนเปื้อนนี้เพียงมองหาแพ็คเกจโถในเวลากลางคืน ใช้แพ็คเกจ Maven เพื่อนำเข้ามากที่สุดเพราะ Maven สามารถลดความขัดแย้งของรุ่นและข้อได้เปรียบอื่น ๆ
ฉันสามารถพูดได้ว่าคุณสามารถใช้ฟังก์ชั่นการเพจที่ง่ายขึ้นนี้โดยเร็วที่สุด หากคุณไม่เข้าใจโปรดเพิ่มฉันใน QQ และพูดคุยกัน อย่าสาบาน! นอกจากนี้บทความอาจมีขนาดค่อนข้างใหญ่ แต่ใช้เวลาสักครู่อ่านและฝึกฝนมันจะได้รับมาก
ขั้นตอนที่ 1: เนื่องจากหัวข้อหมุนรอบวิธีการแบ่งแยกให้เริ่มต้นด้วย mybatis ก่อนอื่นเราจะนำไฟล์การกำหนดค่าที่สำคัญอีกสองไฟล์ที่เกี่ยวข้องกับ MyBatis เพื่อความเข้าใจสั้น ๆ หนึ่งคือ mybatis-config.xml และอื่น ๆ คือไฟล์การกำหนดค่า Mapper ที่สอดคล้องกับเอนทิตี ฉันจะเขียนความคิดเห็นเกี่ยวกับไฟล์การกำหนดค่าและทุกคนจะเข้าใจได้อย่างรวดเร็ว
mybatis-config.xml
<! การกำหนดค่า doctype สาธารณะ "-// mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <การกำหนดค่า> <! -> <การตั้งค่าชื่อ = "cacheenabled" value = "false"/> <!-เปิดใช้งานหรือปิดใช้งานการโหลดขี้เกียจทั่วโลก เมื่อปิดใช้งานวัตถุที่เกี่ยวข้องทั้งหมดจะถูกโหลดทันที -> <การตั้งค่าชื่อ = "lazyloadingenabled" value = "true"/> <!-เมื่อเปิดใช้งานวัตถุที่มีคุณสมบัติการโหลดขี้เกียจจะโหลดคุณสมบัติใด ๆ อย่างสมบูรณ์เมื่อเรียกว่า มิฉะนั้นคุณสมบัติแต่ละคุณสมบัติจะถูกโหลดตามต้องการ -> <การตั้งค่าชื่อ = "aggressivelazyloading" value = "true"/> <!-ไม่ว่าจะอนุญาตให้ SQL เดี่ยวส่งคืนชุดข้อมูลหลายชุด (ขึ้นอยู่กับความเข้ากันได้ของไดรเวอร์) ค่าเริ่มต้น: จริง-> <การตั้งค่าชื่อ = "multipleSultSeTsenabled" true "/> <! name = "usecolumnlabel" value = "true"/> <!- อนุญาตให้ JDBC สร้างคีย์หลัก จำเป็นต้องมีการสนับสนุนไดรฟ์ หากตั้งค่าเป็นจริงการตั้งค่านี้จะบังคับให้คีย์หลักที่สร้างขึ้นไดรฟ์บางตัวไม่เข้ากัน แต่ยังสามารถดำเนินการได้ ค่าเริ่มต้น: false-> <การตั้งค่าชื่อ = "useGeneratedKeys" value = "false"/> <!-ระบุว่า mybatis แผนที่คอลัมน์ฐานข้อมูลโดยอัตโนมัติไม่มี: ไม่ปิดบังบางส่วน: ส่วนเต็ม: ทั้งหมด-> <การตั้งค่าชื่อ = "AutomappingBeHavior" คำสั่งและการอัปเดตแบบแบตช์)-> <การตั้งค่าชื่อ = "defaultExecutortype" value = "simple"/> <!-แปลงฟิลด์โดยใช้ Camel NeMenclature -> <การตั้งค่าชื่อ = "mapunderscoretocamelcase" value = "true"/> <!-การตั้งค่าช่วงแคชในพื้นที่: จะมีคำสั่งการแบ่งปันข้อมูล: ขอบเขตคำสั่ง (นี่จะไม่เป็นการแชร์ข้อมูล) defalut: เซสชัน-> <การตั้งค่าชื่อ = พิมพ์เมื่อใส่ค่า null-> <การตั้งค่าชื่อ = "jdbcTypeforNull" value = "null"/> <การตั้งค่าชื่อ = "logPrefix" value = "dao."/> </การตั้งค่า> <! ALIAS = "ผู้ใช้"> </typealias> <typealias type = "com.store.base.secondmodel.pratice.model.product" alias = "ผลิตภัณฑ์"> </typealias> <typealias type = "com.store.base.secondmodel.base.page" การสกัดกั้นหน้าสำหรับ myBatis และเราจำเป็นต้องใช้หน้านี้สกัดกั้นตัวเอง -> <ปลั๊กอิน> <ปลั๊กอิน interceptor = "com.store.base.secondModel.base.pageInterceptor.paginationInterceptor"/> </plugins>
ProductMapper.xml ใช้เป็นวัตถุทดสอบและไฟล์ mapper นี้เพียงกำหนดค่าคำสั่งการสืบค้นที่ต้องใช้
<? xml version = "1.0" การเข้ารหัส = "utf-8"?> <! doctype mapper สาธารณะ "-// mybatis.org//dtd mapper 3.0 // en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" namespace = "com.store.base.secondmodel.pratice.dao.productdao"> <sql id = "basecolumns"> id, product_name เป็น productname, product_no เป็นผลิตภัณฑ์, ราคาเป็นราคา </sql> <select id = "FindList" resultType = "com.store.base.secondmodel.pratice.model.product"> เลือก <รวม refid = "basecolumns"/> จาก t_store_product </select> </mapper>
ขั้นตอนที่ 2: ถัดไปเราจะทำการวิเคราะห์เชิงลึกและการเรียนรู้สำหรับการดักจับการปนเปื้อนนี้ส่วนใหญ่รวมถึงคลาสต่อไปนี้และอินเทอร์เฟซที่เกี่ยวข้อง
(1) คลาสพื้นฐานการสกัดกั้น baseInterceptor
(2) PaginationInterceptor คลาสปลั๊กอิน pagination ที่เราต้องการใช้สืบทอดคลาสพื้นฐานด้านบน
(3) SQLHELPER ส่วนใหญ่จะใช้เพื่อเรียกใช้งบการนับล่วงหน้าและเพื่อให้ได้คำสั่งการแบ่งหน้าทั้งหมดทั้งหมด
(4) ภาษาถิ่น, mysqldialect ส่วนใหญ่ใช้เพื่อว่าฐานข้อมูลรองรับคำสั่ง จำกัด หรือไม่จากนั้นห่อหุ้มคำสั่ง จำกัด ที่สมบูรณ์
ต่อไปนี้เป็นจอแสดงผลการแชร์ของหมวดหมู่เหล่านี้
baseinterceptor.java
แพ็คเกจ com.store.base.secondmodel.base.pageinterceptor; นำเข้า java.io.serializable; นำเข้า java.util.properties; นำเข้า org.apache.ibatis.logging.log; นำเข้า org.apache.ibatis.logging.logfactory; นำเข้า org.apache.ibatis.plugin.interceptor; นำเข้า com.store.base.secondmodel.base.global; นำเข้า com.store.base.secondmodel.base.page; นำเข้า com.store.base.secondmodel.base.dialect.dialect; นำเข้า com.store.base.secondmodel.base.dialect.mysqldialect; นำเข้า com.store.base.util.reflections; / ** * mybatis pagination interceptor คลาสฐาน * @author yiyong_wu * */ บทคัดย่อคลาสสาธารณะคลาส baseinterceptor ใช้ interceptor, serializable {ส่วนตัวคงที่ long serialversionuid = 1l; ได้รับการป้องกันสตริงสุดท้ายคงที่ = "หน้า"; ได้รับการป้องกันสตริงสุดท้ายที่ได้รับการป้องกัน = "มอบหมาย"; ได้รับการป้องกันสตริงสุดท้ายที่ได้รับการป้องกัน mapped_statement = "MappedStatement"; บันทึกบันทึกการป้องกัน = logfactory.getLog (this.getClass ()); ภาษาถิ่นที่ได้รับการป้องกัน / *** แปลงและตรวจสอบพารามิเตอร์* @param พารามิเตอร์พารามิเตอร์พารามิเตอร์พารามิเตอร์ ParameterObject* @param หน้าวัตถุการแบ่งหน้า* @@return pagination Object* @throws พารามิเตอร์ nosuchfieldException ไม่สามารถพบได้*/ @suppresswarnings ("Unchecked") หน้า) {return (page <jobch>) parameterObject; } else {return (page <jobch>) reflections.getFieldValue (ParameterObject, หน้า); }} catch (exception e) {return null; }} /*** ตั้งค่าคุณสมบัติรองรับคลาสภาษาถิ่นที่กำหนดเองและวิธีกำหนดฐานข้อมูล* <code> DialectClass </code> คลาสภาษาถิ่นที่กำหนดเอง สิ่งนี้สามารถกำหนดค่าได้โดยไม่ต้องกำหนดค่า * <oDe> DBMS </DoE> ประเภทฐานข้อมูลฐานข้อมูลที่รองรับโดยปลั๊กอิน * <code> SQLPattern </code> SQL ID ที่ต้องสกัดกั้น * @Param P Properties */Void InitProperties สตริง dbType = global.getConfig ("jdbc.type"); if ("mysql" .equals (dbType)) {Dialect = new MySqldialect (); } if (dalect == null) {โยน runtimeException ใหม่ ("MyBatis Dialect Error"); } ภาษาถิ่น = ภาษาถิ่น; -PaginationInterceptor.java
แพ็คเกจ com.store.base.secondmodel.base.pageinterceptor; นำเข้า java.util.properties; นำเข้า org.apache.ibatis.executor.executor; นำเข้า org.apache.ibatis.mapping.boundsql; นำเข้า org.apache.ibatis.mapping.mappedstatement; นำเข้า org.apache.ibatis.mapping.sqlsource; นำเข้า org.apache.ibatis.plugin.intercepts; นำเข้า org.apache.ibatis.plugin.invocation; นำเข้า org.apache.ibatis.plugin; นำเข้า org.apache.ibatis.plugin.signature; นำเข้า org.apache.ibatis.reflection.metaobject; นำเข้า org.apache.ibatis.session.resulthandler; นำเข้า org.apache.ibatis.session.rowbounds; นำเข้า com.store.base.secondmodel.base.page; นำเข้า com.store.base.secondmodel.base.util.stringutils; นำเข้า com.store.base.util.reflections; /*** ปลั๊กอินเพจฐานข้อมูลเพียงสกัดกั้นคำสั่งค้นหาเท่านั้น * @author yiyong_wu * */ @intercepts ({@signature (type = executor.class, method = "query", args = {mappedstatement.class, object.class, rowbounds.class, resulthandler.class}) @Override การสกัดกั้นวัตถุสาธารณะ (การเรียกร้องการเรียกใช้) โยนได้ {สุดท้าย mappedStatement mappedStatement = (mappedStatement) ravecocation.getArgs () [0]; พารามิเตอร์ object = rachation.getArgs () [1]; BoundSQL BUNTSQL = MappedStatement.getBoundSQL (พารามิเตอร์); พารามิเตอร์ Object = BoundSql.GetParameterObject (); // รับหน้าวัตถุพารามิเตอร์ pagination <jobch> page = null; if (parameterObject! = null) {page = convertParameter (parameterObject, page); } // หากตั้งค่าวัตถุเพจเพจการเพจจะดำเนินการถ้า (หน้า! = null && page.getPagesize ()! = -1) {ถ้า (stringutils.isblank (boundsql.getsql ()))) {return null; } String OriginalsQl = BoundSql.GetSql (). trim (); // รับจำนวนทั้งหมดของ page.setCount (sqlhelper.getCount (OriginalsQl, NULL, MappedStatement, ParameterObject, BoundSQL, log)); // การสืบค้นเพดานปากที่แปลเป็นภาษาท้องถิ่นเพื่อแก้ไขฐานข้อมูลและให้ความสนใจในการปรับเปลี่ยนสตริงการใช้งาน PageSQL = SQLHELPER.GeneratePagesQL (OriginalSQL, หน้าภาษา); Invocation.getArgs () [2] = ใหม่ Rowbounds (rowbounds.no_row_offset, rowbounds.no_row_limit); BoundSQL NewBoundSQL = New BoundSQL (MappedStatement.getConfiguration (), PagesQl, BoundSQL.GetParameterMappings (), BoundSQL.GetParameterObject ()); // แก้ mybatis pagination foreach พารามิเตอร์ความล้มเหลวเริ่มต้นถ้า (reflections.getfieldValue (boundsql, "metaparameters")! = null) {metaobject mo = (metaobject) reflections.getfieldValue (boundsql, "metaparameters"); Reflections.setfieldValue (Newboundsql, "Metaparameters", MO); } // แก้ Mybatis pagination foreach parameter ความล้มเหลวสิ้นสุด MappedStatement newms = CopyFrommappedStatement (MappedStatement, BoundSQLSQLSource ใหม่ (NewBoundSQL)); Invocation.getArgs () [0] = newms; } return invocation.proceed (); } @Override ปลั๊กอินวัตถุสาธารณะ (เป้าหมายวัตถุ) {return plugin.wrap (เป้าหมาย, สิ่งนี้); } @Override โมฆะสาธารณะ setProperties (คุณสมบัติคุณสมบัติ) {super.InitProperties (คุณสมบัติ); } Private MappedStatement CopyFrommappedStatement (MappedStatement MS, SQLSource NewsQlSource) {MappedStatement.Builder Builder = ใหม่ MappedStatement.builder (Ms.GetConfiguration (), Ms.getid () builder.resource (Ms.getResource ()); builder.fetchSize (Ms.GetFetchSize ()); builder.statementType (Ms.getStatementType ()); Builder.keyGenerator (Ms.getKeyGenerator ()); if (ms.getKeyProperties ()! = null) {สำหรับ (สตริง keyProperty: ms.getKeyProperties ()) {builder.keyProperty (keyProperty); }} builder.timeout (ms.gettimeout ()); builder.parametermap (Ms.getParameterMap ()); builder.resultmaps (Ms.GetResultMaps ()); builder.cache (Ms.getCache ()); return builder.build (); } Public Static Class BoundSQLSQLSource ใช้ SQLSource {BoundSQL BoundSQL; Public BoundsqlsqlSource (BoundSQL BUNTSQL) {this.boundsql = boundsql; } @Override Public Boundsql getBoundSQL (พารามิเตอร์วัตถุ) {return boundSQL; -sqlhelper.java
แพ็คเกจ com.store.base.secondmodel.base.pageinterceptor; นำเข้า java.sql.connection; นำเข้า java.sql.preparedStatement; นำเข้า java.sql.resultset; นำเข้า java.sql.sqlexception; นำเข้า java.util.list; นำเข้า java.util.regex.matcher; นำเข้า java.util.regex.pattern; นำเข้า org.apache.ibatis.executor.errorContext; นำเข้า org.apache.ibatis.executor.executorexception; นำเข้า org.apache.ibatis.logging.log; นำเข้า org.apache.ibatis.mapping.boundsql; นำเข้า org.apache.ibatis.mapping.mappedstatement; นำเข้า org.apache.ibatis.mapping.parametermapping; นำเข้า org.apache.ibatis.mapping.parametermode; นำเข้า org.apache.ibatis.reflection.metaobject; นำเข้า org.apache.ibatis.reflection.property.propertytokenizer; นำเข้า org.apache.ibatis.scripting.xmltags.foreachsqlnode; นำเข้า org.apache.ibatis.session.configuration; นำเข้า org.apache.ibatis.type.typehandler; นำเข้า org.apache.ibatis.type.typehandlerregistry; นำเข้า com.store.base.secondmodel.base.global; นำเข้า com.store.base.secondmodel.base.page; นำเข้า com.store.base.secondmodel.base.dialect.dialect; นำเข้า com.store.base.secondmodel.base.util.stringutils; นำเข้า com.store.base.util.reflections; /*** คลาสเครื่องมือ SQL* @author yiyong_wu** /คลาสสาธารณะ sqlhelper { /*** ตัวสร้างส่วนตัวเริ่มต้น* /ส่วนตัว sqlhelper () {} /*** ตั้งค่าสำหรับพารามิเตอร์ SQL (?) SQL วัตถุของคำสั่ง * @param mappedStatement mappedStatement * @param boundsql sql * @param พารามิเตอร์พารามิเตอร์พารามิเตอร์พารามิเตอร์พารามิเตอร์ @throws java.sql.sqlexception database ข้อยกเว้น */ @suppresswarnings boundSQL, พารามิเตอร์วัตถุ) พ่น sqlexception {errorContext.Instance (). กิจกรรม ("การตั้งค่าพารามิเตอร์"). วัตถุ (mappedStatement.getParameterMap (). getId ()); รายการ <ParameterMapping> ParameterMappings = boundSQL.GetParameterMappings (); if (parameterMappings! = null) {การกำหนดค่าการกำหนดค่า = mappedStatement.getConfiguration (); typeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry (); MetaObject metaObject = parameterObject == null? null: configuration.newmetaObject (parameterObject); สำหรับ (int i = 0; i <parametermappings.size (); i ++) {parametermapping parametermapping = parametermappings.get (i); if (parameterMapping.getMode ()! = parameterMode.out) {ค่าวัตถุ; String propertyName = parameterMapping.getProperty (); PropertyTokenizer prop = new PropertyTokenizer (PropertyName); if (parameterObject == null) {value = null; } อื่นถ้า (typeHandlerRegistry.hastypehandler (parameterObject.getClass ())) {value = parameterObject; } อื่นถ้า (boundsql.hasadditionalParameter (PropertyName)) {value = boundSql.GetAdDitionAlParameter (PropertyName); } else if (propertyName.startswith (foreachsqlnode.item_prefix) && boundsql.hasadditionalparameter (prop.getName ())) {value = boundsql.getAdditionalParameter (prop.getName ()); if (value! = null) {value = configuration.newMetaObject (value) .getValue (propertyName.SubString (prop.getName (). length ())); }} else {value = metaObject == null? null: metaobject.getValue (PropertyName); } @suppresswarnings ("rawtypes") typeHandler typeHandler = parametermapping.getTypehandler (); if (typeHandler == null) {โยน executorexception ใหม่ ("ไม่พบ typeHandler สำหรับพารามิเตอร์" + propertyName + "ของคำสั่ง" + mappedStatement.getId ()); } typeHandler.SetParameter (PS, I + 1, ค่า, parameterMapping.getjdbctype ()); }}}} / *** การสืบค้นบันทึกทั้งหมด* @param SQL SQL คำสั่ง* @param การเชื่อมต่อฐานข้อมูลการเชื่อมต่อ* @param mappedStatement แมป* @param พารามิเตอร์พารามิเตอร์* @param boundsql boundsql* @return จำนวนทั้งหมด MappedStatement MappedStatement, ParameterObject วัตถุสุดท้าย, ขอบเขตสุดท้าย BoundSQL BoundSQL, บันทึกบันทึก) พ่น sqlexception {String dbname = global.getConfig ("jdbc.type"); สตริงสุดท้าย countsql; if ("Oracle" .equals (dbname)) {countsql = "เลือกนับ (1) จาก (" + sql + ") tmp_count"; } else {countsql = "เลือกนับ (1) จาก (" + removeOrders (sql) + ") tmp_count"; } การเชื่อมต่อ conn = การเชื่อมต่อ; PreparedStatement PS = NULL; ผลลัพธ์ RS = NULL; ลอง {ถ้า (log.isdebugenabled ()) {log.debug ("นับ SQL:" + stringUtils.replaceeach (countsql, สตริงใหม่ [] {"/n", "/t"}, สตริงใหม่ [] {"", ""}); } if (conn == null) {conn = mappedStatement.getConfiguration (). getenvironment (). getDataSource (). getConnection (); } ps = conn.prepareStatement (countsql); BoundSQL COUNTBS = New BoundSQL (MappedStatement.getConfiguration (), CountsQl, BoundSQL.GetParameterMappings (), ParameterObject); // แก้ mybatis pagination foreach พารามิเตอร์ความล้มเหลวเริ่มต้นถ้า (reflections.getfieldValue (boundsql, "metaparameters")! = null) {metaobject mo = (metaobject) reflections.getfieldValue (boundsql, "metaparameters"); Reflections.setfieldValue (Countbs, "Metaparameters", MO); } // แก้ Mybatis pagination foreach parameter failure สิ้นสุด sqlhelper.setparameters (PS, MappedStatement, Countbs, ParameterObject); rs = ps.executeQuery (); จำนวน int = 0; if (rs.next ()) {count = rs.getInt (1); } นับคืน; } ในที่สุด {ถ้า (rs! = null) {rs.close (); } if (ps! = null) {ps.close (); } if (conn! = null) {conn.close (); }}} / *** สร้างหน้าเฉพาะตามฐานข้อมูลภาษาถิ่น* @param SQL SQL คำสั่งใน @Param SQL Mapper* @Param หน้าเพจเพจวัตถุ* @param ภาษาถิ่นภาษาถิ่น* @return paging sql* / สตริงคงที่สาธารณะ ส่งคืน Dialect.getLimitString (sql, page.getFirstResult (), page.getMaxResults ()); } else {return sql; }} /*** ลบประโยคที่เลือกของ QLString * @param hql * @return */ @suppresswarnings ("unused") สตริงคงที่ส่วนตัวลบ (สตริง qlstring) {int beginpos = qlstring.toLowerCase (). indexof ("จาก"); return qlString.substring (beginpos); } /*** ลบส่วนคำสั่งซื้อของ HQL *@param hql *@return */สตริงคงที่ส่วนตัว removeOrders (string qlstring) {pattern p = pattern.compile ("order // s *โดย [// w | // w | // s | // s] *", pattern.case_insensitive); matcher m = p.matcher (qlstring); StringBuffer sb = new StringBuffer (); ในขณะที่ (m.find ()) {m.appendreplacement (sb, ""); } M.AppendTail (SB); ส่งคืน sb.toString (); -Interface Dialect.java
แพ็คเกจ com.store.base.secondmodel.base.dialect; / *** คล้ายกับไฮเบอร์เนต แต่มีเพียงส่วนเพจที่เรียบง่าย* @author yiyong_wu**/ อินเทอร์เฟซสาธารณะภาษาถิ่น {/ *** ฐานข้อมูลนั้นสนับสนุนวิธีการสืบค้นเพจเพจปัจจุบันสำหรับการเพจ* หากฐานข้อมูลไม่สนับสนุน / ** * แปลง SQL เป็น pagination SQL และเรียก Paging SQL แยกกัน * * @Param SQL SQL คำสั่ง * @param หมายเลขออฟเซ็ตของการเริ่มต้น * @Param ขีด จำกัด จำนวนบันทึกที่แสดงต่อหน้า * @return SQL -mysqldialect.java
แพ็คเกจ com.store.base.secondmodel.base.dialect; / ** * การใช้ภาษา MySQL * @author yiyong_wu * */ คลาสสาธารณะ MySqldialect ใช้ภาษาถิ่น {@Override Public Public SupportLimit () {return true; } @Override สตริงสาธารณะ getLimitString (สตริง SQL, ออฟเซ็ต int, ขีด จำกัด int) {return getLimitString (SQL, Offset, Integer.ToString (ชดเชย), Integer.ToString (ขีด จำกัด )); } /*** เปลี่ยน SQL เป็นคำสั่ง SQL ที่เพจทำให้การเปลี่ยนชดเชยและ จำกัด ด้วยตัวยึดตำแหน่ง * <pre> * ตัวอย่างเช่น MySQL * Dialect.getLimitString ("เลือก * จากผู้ใช้", 12, ": Offset", 0, ": Limit") จะส่งคืน * เลือก * จากขีด จำกัด ของผู้ใช้: ออฟเซ็ต,: จำกัด * </pre> * @param ตัวยึด @return pagination SQL ที่มีตัวยึดตำแหน่ง */ สตริงสาธารณะ getLimitString (สตริง SQL, int ออฟเซ็ต, สตริงออฟเซ็ตโฮลเดอร์, สตริง จำกัด ผู้ถือหุ้น) {StringBuilder StringBuilder = StringBuilder ใหม่ StringBuilder.Append ("Limit"); if (Offset> 0) {StringBuilder.Append (OffsetPlaceholder) .append (","). ภาคผนวก (LimmentPlaceHolder); } else {stringbuilder.append (LimmentPlaceHolder); } return stringbuilder.toString (); -เกือบที่นี่เราได้แบ่งปันวิธีการใช้งานทั้งหน้า แต่เรามีงานที่สำคัญกว่า หากเราต้องการให้ทุกอย่างวิ่งเราต้องมีงานพื้นฐานที่ต้องทำ ต่อไปเราวิเคราะห์ชุดวัตถุหน้าทั้งหมดและสถาปัตยกรรมสามชั้นที่ใช้และใช้ผลิตภัณฑ์เป็นเอนทิตีสำหรับการวิเคราะห์ หลังจากพูดคุยเกี่ยวกับสถาปัตยกรรมสามชั้นที่สมบูรณ์รางวัลจะเต็มแน่นอน มาพูดถึงเรื่องนี้ตามลำดับของเอนทิตี-> dao-> บริการในทางกลับกัน
ก่อนอื่นเราต้องสืบทอดสองคลาสนามธรรมที่เป็นนามธรรมและข้อมูลสำหรับนิติบุคคลของเรา
Baseentity.java ส่วนใหญ่วางตัวแปรสมาชิกหน้า หลังจากสืบทอดมันแต่ละเอนทิตีสามารถมีตัวแปรสมาชิกนี้
แพ็คเกจ com.store.base.secondmodel.base; นำเข้า java.io.serializable; นำเข้า java.util.map; นำเข้า javax.xml.bind.annotation.xmlTransient; นำเข้า org.apache.commons.lang3.Stringutils; นำเข้า org.apache.commons.lang3.builder.reflectiontostostringbuilder; นำเข้า com.fasterxml.jackson.annotation.jsonignore; นำเข้า com.google.common.collect.maps; นำเข้า com.store.base.model.storeuser; / ** * เอนทิตีระดับบนสุด * @author yiyong_wu * * @param <t> */ บทคัดย่อระดับสาธารณะ Baseentity <t> ใช้ serializable {ส่วนตัวคงที่สุดท้าย Long SerialVersionUid = 1l; / ** * ลบแท็ก (0: ปกติ; 1: ลบ; 2: การตรวจสอบ;) */ สตริงสุดท้ายคงที่สาธารณะ del_flag_normal = "0"; สตริงสุดท้ายคงที่สาธารณะ del_flag_delete = "1"; สตริงสุดท้ายคงที่สาธารณะ del_flag_audit = "2"; / *** หมายเลขเอนทิตี (ตัวระบุที่ไม่ซ้ำกัน)*/ รหัสสตริงที่ได้รับการป้องกัน; / *** ผู้ใช้ปัจจุบัน*/ Proftected StoreUser CurrentUser; / *** วัตถุ pagination เอนทิตีปัจจุบัน*/ หน้าป้องกัน <T> หน้า; / ** * Custom SQL (ตัวระบุ SQL, เนื้อหา SQL) */ แผนที่ส่วนตัว <สตริง, สตริง> SQLMAP; public baseentity () {} public baseentity (string id) {this (); this.id = id; } สตริงสาธารณะ getId () {return id; } โมฆะสาธารณะ setId (รหัสสตริง) {this.id = id; } / *** สิ่งนี้จะถูกเรียกเมื่อทำการปรับปรุงการอัปเดตสำหรับ Shiro เพื่อรับผู้ใช้ปัจจุบัน* @return* / @jsonignore @xmlTransient public StoreUser GetCurrentUser () {ถ้า (currentUser == null) {// currentUser = userUtils.getUser (); } return currentUser; } โมฆะสาธารณะ setCurrentUser (StoreUser CurrentUser) {this.CurrentUser = CurrentUser; } @JSONIGNORE @XMLTransient หน้าสาธารณะ <t> getPage () {if (page == null) {page = หน้าใหม่ <> (); } หน้าคืน; } หน้าสาธารณะ <t> setPage (หน้า <t> หน้า) {this.page = page; หน้ากลับ; } @JSONIGNORE @xMlTransient แผนที่สาธารณะ <สตริง, สตริง> getSQlMap () {ถ้า (sqlmap == null) {sqlmap = maps.newhashmap (); } ส่งคืน sqlmap; } โมฆะสาธารณะ setsqlmap (แผนที่ <สตริงสตริง> sqlmap) {this.sqlmap = sqlmap; } / ** * ดำเนินการวิธีการก่อนการแทรก subclass ใช้งาน * / โมฆะนามธรรมสาธารณะ preinsert (); / ** * ดำเนินการวิธีการก่อนการอัปเดต, subclass ดำเนินการ */ นามธรรมนามธรรมสาธารณะ preUpdate (); /*** ไม่ว่าจะเป็นเร็กคอร์ดใหม่ (ค่าเริ่มต้น: เท็จ), call setisNewRecord () เพื่อตั้งค่าระเบียนใหม่และใช้ ID ที่กำหนดเอง * หลังจากตั้งค่าเป็นจริงคำสั่งแทรกจะถูกบังคับให้ดำเนินการ ID จะไม่ถูกสร้างขึ้นโดยอัตโนมัติและจำเป็นต้องส่งผ่านด้วยตนเอง * @return */ บูลีนสาธารณะ getIsNewRecord () {return stringutils.isblank (getId ()); } / *** วัตถุตัวแปรทั่วโลก* / @JSONIGNORE Global GetGlobal () {return Global.getInstance (); } / *** รับชื่อฐานข้อมูล* / @jsonignore สตริงสาธารณะ getDbName () {return global.getConfig ("jdbc.type"); } @Override สตริงสาธารณะ toString () {return reflectionToStringBuilder.toString (นี่); -DataEntity.java ส่วนใหญ่จัดเก็บการอัปเดตและลบเวลาสร้างผู้ใช้อัปเดตผู้ใช้การตั้งค่าสถานะการลบแบบลอจิคัล ฯลฯ
แพ็คเกจ com.store.base.secondmodel.base; นำเข้า java.util.date; นำเข้า org.hibernate.validator.constraints.length; นำเข้า com.fasterxml.jackson.annotation.jsonformat; นำเข้า com.fasterxml.jackson.annotation.jsonignore; นำเข้า com.store.base.model.storeuser; / ** * เอนทิตีข้อมูล * @author yiyong_wu * * @param <t> */ dataentity คลาสบทคัดย่อสาธารณะ <t> ขยาย baseentity <t> {ส่วนตัวคงที่ความยาวคงสุดท้าย Protected StoreUser CreateBy; // ผู้สร้างวันที่ได้รับการป้องกันที่สร้างขึ้น; // วันที่สร้างการป้องกัน reputidy by; // อัปเดตวันที่ได้รับการปรับปรุง // อัปเดตวันที่ได้รับการป้องกันสตริง delflag; // ลบแท็ก (0: ปกติ; 1: ลบ; 2: การตรวจสอบ) ข้อมูลสาธารณะ () {super (); this.delflag = del_flag_normal; } public dataEntity (string id) {super (id); } / ** * ดำเนินการวิธีการก่อนการแทรกคุณต้องโทรด้วยตนเอง * / @Override โมฆะสาธารณะ preinsert () {// ไม่มีข้อ จำกัด เกี่ยวกับ ID ไปยัง UUID, โทร SetIsNewRecord () เพื่อใช้รหัสที่กำหนดเอง // ผู้ใช้ = ผู้ใช้ // ถ้า (stringUtils.isNotBlank (user.getId ())) {// this.updateBy = ผู้ใช้; // this.createBy = ผู้ใช้; //} this.updatedate = วันที่ใหม่ (); this.created = this.updatedate; } / ** * ดำเนินการวิธีการก่อนอัปเดตคุณต้องโทรด้วยตนเอง * / @Override โมฆะสาธารณะ preUpdate () {// ผู้ใช้ผู้ใช้ = userUtils.getUser (); // ถ้า (stringUtils.isNotBlank (user.getId ())) {// this.updateBy = ผู้ใช้; //} this.updatedate = วันที่ใหม่ (); } // @jsonignore Public StoreUser GetCreateBy () {return createBy; } โมฆะสาธารณะ setCreateBy (storeUser createBy) {this.createBy = createBy; } @jsonformat (pattern = "yyyy-mm-dd hh: mm: ss") วันที่สาธารณะ getcreatedate () {return createdate; } โมฆะสาธารณะ setCreatedate (วันที่ที่สร้างขึ้น) {this.createdate = สร้างขึ้น; } // @JSONIGNORE Public StoreUser GetUpDateBy () {return updateBy; } โมฆะสาธารณะ setUpDateBy (roptuptyer updateBy) {this.updateBy = updateBy; } @JSONFORMAT (pattern = "yyyy-mm-dd hh: mm: ss") วันที่สาธารณะ getUpdatedate () {return updatedate; } โมฆะสาธารณะ setUpDatedate (วันที่อัปเดต) {this.updatedate = updateDate; } @jsonignore @Length (min = 1, max = 1) สตริงสาธารณะ getDelflag () {return delflag; } โมฆะสาธารณะ setDelflag (สตริง delflag) {this.delflag = delflag; -Product.java หมวดหมู่ผลิตภัณฑ์
แพ็คเกจ com.store.base.secondmodel.pratice.model; นำเข้า com.store.base.secondmodel.base.dataentity; / ***คลาสพื้นฐานของผลิตภัณฑ์*11 ตุลาคม 2016*yiyong_wu*/ ผลิตภัณฑ์ระดับสาธารณะขยาย DataEntity <Product> {ส่วนตัวคงที่สุดท้าย Long SerialVersionUid = 1L; Private String ProductName; ราคาลอยตัวส่วนตัว Private String Productno; สตริงสาธารณะ getProductName () {return productName; } โมฆะสาธารณะ setProductName (String productName) {this.productName = productName; } public float getPrice () {ราคาคืน; } โมฆะสาธารณะ setPrice (ราคาลอย) {this.price = ราคา; } สตริงสาธารณะ getProductNo () {return productno; } โมฆะสาธารณะ setProductNo (สตริง productno) {this.productNo = productNo; -แล้วล่ะ? คุณเห็นความสัมพันธ์การสืบทอดนิติบุคคลที่ซับซ้อนมากหรือไม่? แต่มีอะไร? ยิ่งมันซับซ้อนมากเท่าไหร่ก็ยิ่งสมบูรณ์มากขึ้นเท่านั้น ต่อไปฉันจะดูเลเยอร์สามชั้นเดียวกันพร้อมที่จะรับบัพติสมา
อินเทอร์เฟซสำรอง
แพ็คเกจ com.store.base.secondmodel.base; / ** * อินเทอร์เฟซ DAO สูงสุดสูงสุด * @author yiyong_wu * */ อินเตอร์เฟสสาธารณะที่ใช้ {} cruddao.java เลเยอร์อินเตอร์เฟส DAO สำหรับการลบการลบและการสืบค้น [java] ดูสำเนาธรรมดา? ดูแฟรกเมนต์โค้ดบนรหัสที่ได้จากแพ็คเกจแฟรกเมนต์รหัสของฉัน com.store.base.secondmodel.base; นำเข้า java.util.list; / ** * กำหนดอินเทอร์เฟซ DAO สำหรับการเพิ่มการลบการดัดแปลงและการสืบค้น * @author yiyong_wu * * @param <t> */ อินเตอร์เฟสสาธารณะ cruddao <t> ขยายตาม {/ ** * รับข้อมูลชิ้นเดียว * @param id * @return */ public t รับ / ** * รับข้อมูลชิ้นเดียว * @param Entity * @return */ public t get (t entity); /*** สอบถามรายการข้อมูล หากคุณต้องการเพจโปรดตั้งค่าวัตถุเพจเช่น: entity.setPage (หน้าใหม่ <t> ()); * @param Entity * @return */ รายการสาธารณะ <t> findlist (t entity); / ** * สอบถามรายการข้อมูลทั้งหมด * @param Entity * @return */ รายการสาธารณะ <t> findalllist (t entity); /*** สอบถามรายการข้อมูลทั้งหมด* @See รายการสาธารณะ <t> findAlllist (t entity)* @return รายการสาธารณะ <t> findalllist (); *// ** * แทรกข้อมูล * @Param Entity * @return */ INT INT สาธารณะ (t เอนทิตี); / ** * อัปเดตข้อมูล * @Param Entity * @return */ การอัปเดตสาธารณะ INT (T เอนทิตี); / ** * ลบข้อมูล (โดยปกติการลบลอจิคัลอัปเดตฟิลด์ del_flag เป็น 1) * @param id * @see public int ลบ (t entity) * @return */ public int ลบ (string id); / ** * ลบข้อมูล (โดยปกติการลบเชิงตรรกะอัปเดตฟิลด์ del_flag เป็น 1) * @param Entity * @return */ public int ลบ (t entity); -Productdao.java mybatis Mapper Interface Interface ที่สอดคล้องกันก็เป็นการใช้งาน DAO คุณต้องปรับแต่งคำอธิบายประกอบ @mybatisrepository
แพ็คเกจ com.store.base.secondmodel.pratice.dao; นำเข้า com.store.base.secondmodel.base.cruddao; นำเข้า com.store.base.secondmodel.base.mybatisrepository; นำเข้า com.store.base.secondmodel.pratice.model.product; / ** *todo *11 ตุลาคม 2016 *yiyong_wu */ @mybatisrepository อินเตอร์เฟสสาธารณะ ProductDao ขยาย Cruddao <ผลิตภัณฑ์> {}คำอธิบายประกอบที่กำหนดเอง mybatisrepository.java เกี่ยวข้องกับคำอธิบายประกอบที่กำหนดเอง ฉันจะไม่อธิบายมากเกินไปที่นี่มีข้อมูลออนไลน์มากมาย
แพ็คเกจ com.store.base.secondmodel.base; นำเข้า java.lang.annotation.documented; นำเข้า java.lang.annotation.retention; นำเข้า java.lang.annotation.target; นำเข้า java.lang.annotation.RetentionPolicy; นำเข้า java.lang.annotation.ElementType; นำเข้า org.springframework.stereotype.component; /*** ระบุ dao ของ mybatis เพื่ออำนวยความสะดวกในการสแกน {@link org.mybatis.spring.mapper.mapperscannerconfigurer} * *โปรดทราบว่าคุณต้องการกำหนดค่าการกำหนดค่าเพื่อสแกนคลาส Annotated ในไฟล์การกำหนดค่าสปริง * *<bean id = "mapperscannerConfigurer"> *<ชื่อคุณสมบัติ = "SQLSessionFactoryBeanName" value = "SQLSessionFactory" /> * name = "AnnotationClass" value = "com.store.base.secondmodel.base.mybatisrepository"/> * </bean> * @author yiyong_wu * */@retention ค่า () ค่าเริ่มต้น ""; - หมายเหตุ: ไฟล์ productmapper.xml ที่มีการเชื่อมต่อที่แข็งแกร่งกับ productdao.java เป็นไฟล์ productmapper.xml คุณจะเห็นว่าเนมสเปซของไฟล์การกำหนดค่าด้านบนชี้ไปที่เส้นทางไปยัง DAO นี้
ต่อไปเราเข้าสู่การวิเคราะห์บริการขั้นสุดท้ายและมันก็เป็นมรดกสามชั้น
baseservice.java
แพ็คเกจ com.store.base.secondmodel.base; นำเข้า org.slf4j.logger; นำเข้า org.slf4j.loggerfactory; นำเข้า org.slf4j.loggerfactory; นำเข้า org.springframework.transaction.annotation.transactional; / ** * คลาสบริการระดับบนสุดของบริการ * @author yiyong_wu * */ @transactional (อ่านอย่างจริง = จริง) Public Abstract Class Baseservice {// logger logger ที่ได้รับการป้องกัน = loggerFactory.getLogger (getClass ()); -Crudservice.java การใช้งานส่วนต่อประสานทางธุรกิจที่เกี่ยวข้อง
แพ็คเกจ com.store.base.secondmodel.base; นำเข้า java.util.list; นำเข้า org.springframework.beans.factory.annotation.autowired; นำเข้า org.springframework.transaction.annotation.transactional; / ** * เพิ่มลบแก้ไขและตรวจสอบคลาสฐานบริการ * @author yiyong_wu * * @param <d> * @param <t> */ คลาสนามธรรมสาธารณะ crudservice <d ขยาย cruddao <t> / ** * รับข้อมูลชิ้นเดียว * @param id * @return */ public t get (string id) {return dao.get (id); } / ** * รับข้อมูลชิ้นเดียว * @param Entity * @return * / สาธารณะ t รับ (t entity) {return dao.get (เอนทิตี); } /** * Query list data* @param entity * @return */ public List<T> findList(T entity) { return dao.findList(entity); } /** * Query paging data* @param page paging object* @param entity * @return */ public Page<T> findPage(Page<T> page, T entity) { entity.setPage(page); page.setList(dao.findList(entity)); return page; } /** * Save data (insert or update) * @param entity */ @Transactional(readOnly = false) public void save(T entity) { if (entity.getIsNewRecord()){ entity.preInsert(); dao.insert(entity); }else{ entity.preUpdate(); dao.update(entity); } } /** * Delete data* @param entity */ @Transactional(readOnly = false) public void delete(T entity) { dao.delete(entity); -ProductService.java,去继承CrudService接口,注意起注入dao和实体类型的一种模式
package com.store.base.secondmodel.pratice.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.store.base.secondmodel.base.CrudService; import com.store.base.secondmodel.pratice.dao.ProductDao; import com.store.base.secondmodel.pratice.model.Product; /** *TODO *2016年10月11日*yiyong_wu */ @Service @Transactional(readOnly = true) public class ProductService extends CrudService<ProductDao,Product>{ }我想看到这里的同志已经很不耐烦了。但是如果你错过接下去的一段,基本上刚才看的就快等于白看了,革命的胜利就在后半段,因为整个分页功能围绕的就是一个Page对象,重磅内容终于要出来了,当你把Page对象填充到刚才那个BaseEntity上的时候,你会发现一切就完整起来了,废话不多说,Page对象如下
package com.store.base.secondmodel.base; import java.io.Serializable; import java.util.ArrayList; นำเข้า java.util.list; import java.util.regex.Pattern; นำเข้า javax.servlet.http.httpservletrequest; นำเข้า Javax.servlet.http.httpservletResponse; import com.fasterxml.jackson.annotation.JsonIgnore; import com.store.base.secondmodel.base.util.CookieUtils; import com.store.base.secondmodel.base.util.StringUtils; /** * Pagination class* @author yiyong_wu * * @param <T> */ public class Page<T> implements Serializable{ private static final long serialVersionUID = 1L; private int pageNo = 1; // Current page number private int pageSize = Integer.parseInt(Global.getConfig("page.pageSize")); // Page size, set to "-1" means that no paging is performed (paging is invalid) private long count;// Total number of records, set to "-1" means that the total number is not queried private int first;// Home page index private int last;// Last page index private int prev;// Previous page index private int next;// Next page index private boolean firstPage;// Whether it is the first page private boolean lastPage;// Whether it is the last page private int length = 6;// Display page length private int slider = 1;// Display page length before and after private List<T> list = new ArrayList<>(); private String orderBy = ""; // Standard query is valid, example: updated desc, name asc private String funcName = "page"; // Set the name of the js function called by clicking on the page number. The default is page, and it is used when there are multiple paging objects on a page. private String funcParam = ""; // Additional parameter of the function, the third parameter value. private String message = ""; // Set the prompt message, displayed after "n total number of public Page() { this.pageSize = -1; } /** * Constructor method * @param request Pass the repage parameter to remember the page number * @param response is used to set cookies, remember the page number */ public Page(HttpServletRequest request, HttpServletResponse response){ this(request, response, -2); } /** * Constructor method * @param request Pass the repage parameter to remember the page number * @param response is used to set cookies, remember the page number * @param defaultPageSize The default paging size, if -1 is passed, it is not paged, and all data is returned */ public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize){ // Set page number parameters (pass repage parameter to remember page number) String no = request.getParameter("pageNo"); if (StringUtils.isNumeric(no)){ CookieUtils.setCookie(response, "pageNo", no); this.setPageNo(Integer.parseInt(no)); }else if (request.getParameter("repage")!=null){ no = CookieUtils.getCookie(request, "pageNo"); if (StringUtils.isNumeric(no)){ this.setPageNo(Integer.parseInt(no)); } } // Set the page size parameter (pass the repage parameter to remember the page size) String size = request.getParameter("pageSize"); if (StringUtils.isNumeric(size)){ CookieUtils.setCookie(response, "pageSize", size); this.setPageSize(Integer.parseInt(size)); }else if (request.getParameter("repage")!=null){ no = CookieUtils.getCookie(request, "pageSize"); if (StringUtils.isNumeric(size)){ this.setPageSize(Integer.parseInt(size)); } }else if (defaultPageSize != -2){ this.pageSize = defaultPageSize; } // Set the sorting parameters String orderBy = request.getParameter("orderBy"); if (StringUtils.isNotBlank(orderBy)){ this.setOrderBy(orderBy); } } /** * Constructor* @param pageNo Current page number* @param pageSize Pagination size*/ public Page(int pageNo, int pageSize) { this(pageNo, pageSize, 0); } /** * Constructor* @param pageNo Current page number* @param pageSize Pagination size* @param count Number of data strips*/ public Page(int pageNo, int pageSize, long count) { this(pageNo, pageSize, count, new ArrayList<T>()); } /** * Constructor* @param pageNo Current page number* @param pageSize Page size* @param count Number of data strips* @param list Data object list on this page*/ public Page(int pageNo, int pageSize, long count, List<T> list) { this.setCount(count); this.setPageNo(pageNo); this.pageSize = pageSize; this.list = list; } /** * Initialization parameter*/ public void initialize(){ //1 this.first = 1; this.last = (int)(count / (this.pageSize < 1 ? 20 : this.pageSize) + first - 1); if (this.count % this.pageSize != 0 || this.last == 0) { this.last++; } if (this.last < this.first) { this.last = this.first; } if (this.pageNo <= 1) { this.pageNo = this.first; this.firstPage=true; } if (this.pageNo >= this.last) { this.pageNo = this.last; this.lastPage=true; } if (this.pageNo < this.last - 1) { this.next = this.pageNo + 1; } else { this.next = this.last; } if (this.pageNo > 1) { this.prev = this.pageNo - 1; } else { this.prev = this.first; } //2 if (this.pageNo < this.first) {// If the current page is smaller than the home page this.pageNo = this.first; } if (this.pageNo > this.last) {// If the current page is larger than the last page this.pageNo = this.last; } } /** * Default output current paging tag* <div>${page}</div> */ @Override public String toString() { StringBuilder sb = new StringBuilder(); if (pageNo == first) {// If it is the home page sb.append("<li class=/"disabled/"><a href=/"javascript:/">« Previous page</a></li>/n"); } else { sb.append("<li><a href=/"javascript:/" onclick=/""+funcName+"("+prev+","+pageSize+",'"+funcParam+"');/">« Previous page</a></li>/n"); } int begin = pageNo - (length / 2); if (begin < first) { begin = first; } int end = begin + length - 1; if (end >= last) { end = last; begin = end - length + 1; if (begin < first) { begin = first; } } if (begin > first) { int i = 0; for (i = first; i < first + slider && i < begin; i++) { sb.append("<li><a href=/"javascript:/" onclick=/""+funcName+"("+i+","+pageSize+",'"+funcParam+"');/">" + (i + 1 - first) + "</a></li>/n"); } if (i < begin) { sb.append("<li class=/"disabled/"><a href=/"javascript:/">...</a></li>/n"); } } for (int i = begin; i <= end; i++) { if (i == pageNo) { sb.append("<li class=/"active/"><a href=/"javascript:/">" + (i + 1 - first) + "</a></li>/n"); } else { sb.append("<li><a href=/"javascript:/" onclick=/"+funcName+"("+i+","+pageSize+",'"+funcParam+"');/">" + (i + 1 - first) + "</a></li>/n"); } } if (last - end > slider) { sb.append("<li class=/"disabled/"><a href=/"javascript:/">...</a></li>/n"); end = last - slider; } for (int i = end + 1; i <= last; i++) { sb.append("<li><a href=/"javascript:/" onclick=/"+funcName+"("+i+","+pageSize+",'"+funcParam+"');/">" + (i + 1 - first) + "</a></li>/n"); } if (pageNo == last) { sb.append("<li class=/"disabled/"><a href=/"javascript:/">Next page»</a></li>/n"); } else { sb.append("<li><a href=/"javascript:/" onclick=/""+funcName+"("+next+","+pageSize+",'"+funcParam+"');/">" + "next page»</a></li>/n"); } return sb.toString(); } /** * Get pagination HTML code* @return */ public String getHtml(){ return toString(); } /** * Get the total number of settings* @return */ public long getCount() { return count; } /** * Set the total number of data* @param count */ public void setCount(long count) { this.count = count; if (pageSize >= count){ pageNo = 1; } } /** * Get the current page number* @return */ public int getPageNo() { return pageNo; } /** * Set the current page number* @param pageNo */ public void setPageNo(int pageNo) { this.pageNo = pageNo; } /** * Get the page size* @return */ public int getPageSize() { return pageSize; } /** * Set page size (maximum 500) // > 500 ? 500 : pageSize; * @param pageSize */ public void setPageSize(int pageSize) { this.pageSize = pageSize <= 0 ? 10 : pageSize; } /** * Home page index* @return */ @JsonIgnore public int getFirst() { return first; } /** * Last page index* @return */ @JsonIgnore public int getLast() { return last; } /** * Get the total number of pages* @return getLast(); */ @JsonIgnore public int getTotalPage() { return getLast(); } /** * Is it the first page* @return */ @JsonIgnore public boolean isFirstPage() { return firstPage; } /** * Is it the last page* @return */ @JsonIgnore public boolean isLastPage() { return lastPage; } /** * Previous page index value* @return */ @JsonIgnore public int getPrev() { if (isFirstPage()) { return pageNo; } else { return pageNo - 1; } } /** * Next page index value* @return */ @JsonIgnore public int getNext() { if (isLastPage()) { return pageNo; } else { return pageNo + 1; } } /** * Get the data object list of this page* @return List<T> */ public List<T> getList() { return list; } /** * Set the data object list of this page* @param list */ public Page<T> setList(List<T> list) { this.list = list; initialize(); return this; } /** * Get query sorting string* @return */ @JsonIgnore public String getOrderBy() { // SQL filtering to prevent injection of String reg = "(?:')|(?:--)|(//*(?:.|[//n//r])*?//*/)|" + "(//b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)//b)"; Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); if (sqlPattern.matcher(orderBy).find()) { return ""; } return orderBy; } /** * Set query sorting, standard query is valid, Example: updated desc, name asc */ public void setOrderBy(String orderBy) { this.orderBy = orderBy; } /** * Get the name of the js function called by the click page number* function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;} * @return */ @JsonIgnore public String getFuncName() { return funcName; } /** * Set the name of the js function called by the click page number. The default is page, which is used when there are multiple paging objects on a page. * @param funcName Default is page */ public void setFuncName(String funcName) { this.funcName = funcName; } /** * Get additional parameters of the pagination function* @return */ @JsonIgnore public String getFuncParam() { return funcParam; } /** * Set additional parameters of the pagination function* @return */ public void setFuncParam(String funcParam) { this.funcParam = funcParam; } /** * Set the prompt message, displayed after "n total numbers"* @param message */ public void setMessage(String message) { this.message = message; } /** * Is the pagination valid* @return this.pageSize==-1 */ @JsonIgnore public boolean isDisabled() { return this.pageSize==-1; } /** * Whether to count the total number* @return this.count==-1 */ @JsonIgnore public boolean isNotCount() { return this.count==-1; } /** * Get Hibernate FirstResult */ public int getFirstResult() { int firstResult = (getPageNo() - 1) * getPageSize(); if (firstResult >= getCount()) { firstResult = 0; } return firstResult; } /** * Get Hibernate MaxResults */ public int getMaxResults(){ return getPageSize(); -看完这个Page对象应该稍微有点感觉了吧,然后我在胡乱贴一些相关用到的工具类吧,工具类的话我只稍微提一下,具体大家可以弄到自己的代码上好好解读。
PropertiesLoader.java 用来获取resource文件夹下的常量配置文件
package com.store.base.secondmodel.base.util; นำเข้า java.io.ioException; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; /** * Properties file loading tool class. Multiple properties files can be loaded, * The value of the same attribute in the last loaded file will overwrite the previous value, but System's Property takes precedence. * @author yiyong_wu * */ public class PropertiesLoader { private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class); private static ResourceLoader resourceLoader = new DefaultResourceLoader(); private final Properties properties; public PropertiesLoader(String... resourcesPaths) { properties = loadProperties(resourcesPaths); } public Properties getProperties() { return properties; } /** * Take out the Property, but System's Property takes priority, and the empty string cannot be returned. */ private String getValue(String key) { String systemProperty = System.getProperty(key); if (systemProperty != null) { return systemProperty; } if (properties.containsKey(key)) { return properties.getProperty(key); } กลับ ""; } /** * Take out the String property, but System's Property takes priority. If all are Null, an exception will be thrown. */ public String getProperty(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return value; } /** * Take out the Property of type String, but the Property of the System is preferred. If it is Null, the Default value will be returned. */ public String getProperty(String key, String defaultValue) { String value = getValue(key); return value != null ? value : defaultValue; } /** * Take out the Property of type Integer, but the Property of the System is preferred. If it is Null or the content is wrong, an exception will be thrown. */ public Integer getInteger(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Integer.valueOf(value); } /** * Take out the Integer type Property, but the System's Property takes priority. If all are Null, the Default value will be returned, and an exception will be thrown if the content is wrong*/ public Integer getInteger(String key, Integer defaultValue) { String value = getValue(key); return value != null ? Integer.valueOf(value) : defaultValue; } /** * Take out the Double type Property, but the System's Property is preferred. If all are Null or the content is wrong, an exception will be thrown. */ public Double getDouble(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Double.valueOf(value); } /** * Take out the Double type Property, but the System's Property is preferred. If all are Null, a Default value will be returned. If all are Null, an exception will be thrown. */ public Double getDouble(String key, Integer defaultValue) { String value = getValue(key); return value != null ? Double.valueOf(value) : defaultValue.doubleValue(); } /** * Take out the Property of Boolean type, but the Property of the System is preferred. If all exceptions are thrown for Null, if the content is not true/false, it will return false. */ public Boolean getBoolean(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Boolean.valueOf(value); } /** * Take out the Boolean type Property, but System's Property takes priority. If all are Null, return the Default value, and if the content is not true/false, return false. */ public Boolean getBoolean(String key, boolean defaultValue) { String value = getValue(key); return value != null ? Boolean.valueOf(value) : defaultValue; } /** * Load multiple files, and the file path uses Spring Resource format. */ private Properties loadProperties(String... resourcesPaths) { Properties props = new Properties(); for (String location : resourcesPaths) { InputStream is = null; try { Resource resource = resourceLoader.getResource(location); is = resource.getInputStream(); props.load(is); } catch (IOException ex) { logger.error("Could not load properties from path:" + location , ex); } finally { IOUtils.closeQuietly(is); } } return props; -Global.java 用来获取全局的一些常量,可以是从配置文件中读取的常量,也可以是定义成final static的常量,获取配置文件的话是调用上面那个类进行获取的。
package com.store.base.secondmodel.base; นำเข้า Java.io.File; นำเข้า java.io.ioException; นำเข้า java.util.map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.DefaultResourceLoader; import com.google.common.collect.Maps; import com.store.base.secondmodel.base.util.PropertiesLoader; import com.store.base.secondmodel.base.util.StringUtils; /** * Global configuration class* @author yiyong_wu * */ public class Global { private static final Logger logger = LoggerFactory.getLogger(Global.class); /** * Current object instance*/ private static Global global = new Global(); /** * Save global attribute value*/ private static Map<String, String> map = Maps.newHashMap(); /** * Properties file loading object*/ private static PropertiesLoader loader = new PropertiesLoader("application.properties"); /** * Show/hide public static final String SHOW = "1"; public static final String HIDE = "0"; /** * Yes/No*/ public static final String YES = "1"; public static final String NO = "0"; /** * Status up/down app dedicated*/ public static final String UPSHVELF = "1"; public static final String DOWNSHVELF = "2"; public static final String SEPARATOR = "/"; /** * True/Wrong*/ public static final String TRUE = "true"; public static final String FALSE = "false"; /** * Basic virtual path of uploading file*/ public static final String USERFILES_BASE_URL = "/userfiles/"; /** * For rich text editors, empty divs will be generated at the end */ public static final String ENDS = "<p><br></p>"; /** * Default empty private constructor*/ public Global() { //do nothing in this method,just empty } /** * Get the current object instance*/ public static Global getInstance() { return global; } /** * Get the configuration*/ public static String getConfig(String key) { String value = map.get(key); if (value == null){ value = loader.getProperty(key); map.put(key, value != null ? value : StringUtils.EMPTY); } return value; } /** * Get URL suffix*/ public static String getUrlSuffix() { return getConfig("urlSuffix"); } /** * Page get constant* @see ${fns:getConst('YES')} */ public static Object getConst(String field) { try { return Global.class.getField(field).get(null); } catch (Exception e) { logger.error("Error getting constant", e); } return null; } /** * Get project path* @return */ public static String getProjectPath(){ // If the project path is configured, it will be returned directly, otherwise it will be automatically retrieved. String projectPath = Global.getConfig("projectPath"); if (StringUtils.isNotBlank(projectPath)){ return projectPath; } try { File file = new DefaultResourceLoader().getResource("").getFile(); if (file != null){ while(true){ File f = new File(file.getPath() + File.separator + "src" + File.separator + "main"); if (f == null || f.exists()){ break; } if (file.getParentFile() != null){ file = file.getParentFile(); }else{ break; } } projectPath = file.toString(); } } catch (IOException e) { logger.error("Loading configuration file failed", e); } return projectPath; -CookieUtil.java 从名称就知道是针对获取和存储cookie的一个工具类
package com.store.base.secondmodel.base.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import javax.servlet.http.Cookie; นำเข้า javax.servlet.http.httpservletrequest; นำเข้า Javax.servlet.http.httpservletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Cookie tool class * @author yiyong_wu * */ public class CookieUtils { private static final Logger logger = LoggerFactory.getLogger(CookieUtils.class); /** * Private constructor */ private CookieUtils() { } /** * Set Cookie (generated time is 1 year) * @param name Name * @param value Value */ public static void setCookie(HttpServletResponse response, String name, String value) { setCookie(response, name, value, 60*60*24*365); } /** * Set Cookie * @param name Name * @param value Value * @param maxAge Survival time (units of seconds) * @param uri Path */ public static void setCookie(HttpServletResponse response, String name, String value, String path) { setCookie(response, name, value, path, 60*60*24*365); } /** * Set Cookie * @param name Name * @param value Value * @param maxAge Survival time (units of seconds) * @param uri path */ public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) { setCookie(response, name, value, "/", maxAge); } /** * Set Cookie * @param name Name* @param value Value* @param maxAge Survival time (in seconds) * @param uri path */ public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) { Cookie cookie = new Cookie(name, null); cookie.setPath(path); cookie.setMaxAge(maxAge); try { cookie.setValue(URLEncoder.encode(value, "utf-8")); } catch (UnsupportedEncodingException e) { logger.error("Unsupported encoding", e); } response.addCookie(cookie); } /** * Get the value of the specified cookie* @param name* @return value*/ public static String getCookie(HttpServletRequest request, String name) { return getCookie(request, null, name, false); } /** * Get the value of the specified cookie and delete it. * @param name name* @return value*/ public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) { return getCookie(request, response, name, true); } /** * Get the value of the specified cookie* @param request Request object* @param response Response object* @param name* @param isRemove Whether to remove* @return value*/ public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) { String value = null; Cookie[] cookies = request.getCookies(); if(cookies == null) { return value; } for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { try { value = URLDecoder.decode(cookie.getValue(), "utf-8"); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncoding", e); } if (isRemove) { cookie.setMaxAge(0); response.addCookie(cookie); } } return value; -SpringContextHolder.java 主要是用来在java代码中获取当前的ApplicationContext,需要在spring配置文件中配置这个bean并且懒加载设置成false;
package com.store.base.secondmodel.base.util; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; @Service @Lazy(false) public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); private static ApplicationContext applicationContext = null; /** * Get the ApplicationContext stored in a static variable. */ public static ApplicationContext getApplicationContext() { assertContextInjected(); return applicationContext; } /** * Get the bean from the static variable applicationContext and automatically transform it into the type of the assigned object. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); } /** * Get the bean from the static variable applicationContext and automatically transform it into the type of the assigned object. */ public static <T> T getBean(Class<T> requiredType) { assertContextInjected(); return applicationContext.getBean(requiredType); } @Override public void destroy() throws Exception { SpringContextHolder.clearHolder(); } /** * Implement the ApplicationContextAware interface and inject the Context into a static variable. */ @Override public void setApplicationContext(ApplicationContext applicationContext) { logger.debug("Inject ApplicationContext to SpringContextHolder:{}", applicationContext); SpringContextHolder.applicationContext = applicationContext; if (SpringContextHolder.applicationContext != null) { logger.info("The ApplicationContext in SpringContextHolder is overwritten, the original ApplicationContext is:" + SpringContextHolder.applicationContext); } } /** * Clear the ApplicationContext in SpringContextHolder to Null. */ public static void clearHolder() { if (logger.isDebugEnabled()){ logger.debug("Clear ApplicationContext in SpringContextHolder:" + applicationContext); } applicationContext = null; } /** * Check that the ApplicationContext is not empty. */ private static void assertContextInjected() { Validate.validState(applicationContext != null, "The applicaitonContext property is not injected, please define SpringContextHolder in applicationContext.xml."); -StringUtils.java字符串相关的一个工具类
package com.store.base.secondmodel.base.util; import java.io.UnsupportedEncodingException; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; นำเข้า javax.servlet.http.httpservletrequest; import org.apache.commons.lang3.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.LocaleResolver; import com.store.base.util.Encodes; /** * String help class* @author yiyong_wu * */ public class StringUtils extends org.apache.commons.lang3.StringUtils { private static final char SEPARATOR = '_'; private static final String CHARSET_NAME = "UTF-8"; private static final Logger logger = LoggerFactory.getLogger(StringUtils.class); /** * Convert to byte array* @param str * @return */ public static byte[] getBytes(String str){ if (str != null){ try { return str.getBytes(CHARSET_NAME); } catch (UnsupportedEncodingException e) { logger.error("", e); return new byte[0]; } }else{ return new byte[0]; } } /** * Convert to byte array* @param str * @return */ public static String toString(byte[] bytes){ try { return new String(bytes, CHARSET_NAME); } catch (UnsupportedEncodingException e) { logger.error("", e); return EMPTY; } } /** * Does it contain strings* @param str Verification string* @param strs String group* @return contains return true */ public static boolean inString(String str, String... strs){ if (str != null){ for (String s : strs){ if (str.equals(trim(s))){ return true; }}} return false; } /** * Replace HTML tag method*/ public static String replaceHtml(String html) { if (isBlank(html)){ return ""; } String regEx = "<.+?>"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(html); return m.replaceAll(""); } /** * Replace with HTML recognized by the phone, remove the style and attributes, and keep Enter. * @param html * @return */ public static String replaceMobileHtml(String html){ if (html == null){ return ""; } return html.replaceAll("<([az]+?)//s+?.*?>", "<$1>"); } /** * Replace with HTML recognized by the phone, remove the style and attributes, and keep Enter. * @param txt * @return */ public static String toHtml(String txt){ if (txt == null){ return ""; } return replace(replace(Encodes.escapeHtml(txt), "/n", "<br/>"), "/t", " "); } /** * Thumbnail string (not distinguishing between Chinese and English characters) * @param str Target string* @param length Intercept length* @return */ public static String abbr(String str, int length) { if (str == null) { return ""; } try { StringBuilder sb = new StringBuilder(); int currentLength = 0; for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) { currentLength += String.valueOf(c).getBytes("GBK").length; if (currentLength <= length - 3) { sb.append(c); } else { sb.append("..."); หยุดพัก; }} ส่งคืน sb.toString (); } catch (UnsupportedEncodingException e) { logger.error("", e); } กลับ ""; } /** * Convert to Double type*/ public static Double toDouble(Object val){ if (val == null){ return 0D; } try { return Double.valueOf(trim(val.toString())); } catch (Exception e) { logger.error("", e); return 0D; } } /** * Convert to Float type*/ public static Float toFloat(Object val){ return toDouble(val).floatValue(); } /** * Convert to Long type*/ public static Long toLong(Object val){ return toDouble(val).longValue(); } /** * Convert to Integer type*/ public static Integer toInteger(Object val){ return toLong(val).intValue(); } /** * Get i18n string*/ public static String getMessage(String code, Object[] args) { LocaleResolver localLocaleResolver = SpringContextHolder.getBean(LocaleResolver.class); HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); Locale localLocale = localLocaleResolver.resolveLocale(request); return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale); } /** * Get the user remote address*/ public static String getRemoteAddr(HttpServletRequest request){ String remoteAddr = request.getHeader("X-Real-IP"); if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("X-Forwarded-For"); } if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("Proxy-Client-IP"); } if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("WL-Proxy-Client-IP"); } return remoteAddr != null ? remoteAddr : request.getRemoteAddr(); } /** * Camel nomenclature tool* @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCamelCase(String s) { String s1 =s; if (s1 == null) { return null; } s1 = s.toLowerCase(); StringBuilder sb = new StringBuilder(s1.length()); boolean upperCase = false; for (int i = 0; i < s1.length(); i++) { char c = s1.charAt(i); if (c == SEPARATOR) { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(c)); upperCase = false; } else { sb.append(c); }} ส่งคืน sb.toString (); } /** * Camel nomenclature tool* @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCapitalizeCamelCase(String s) { String s1 = s; if (s1 == null) { return null; } s1 = toCamelCase(s1); return s1.substring(0, 1).toUpperCase() + s1.substring(1); } /** * Camel Nomenclature Tool* @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toUnderScoreCase(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = true; if (i < (s.length() - 1)) { nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); } if ((i > 0) && Character.isUpperCase(c)) { if (!upperCase || !nextUpperCase) { sb.append(SEPARATOR); } upperCase = true; } else { upperCase = false; } sb.append(Character.toLowerCase(c)); } return sb.toString(); } /** * Convert to JS to get the object value and generate the three-item operation to return the result* @param objectString object string* For example: row.user.id * Return: !row?'':!row.user?'':row.user.id */ public static String jsGetVal(String objectString){ StringBuilder result = new StringBuilder(); StringBuilder val = new StringBuilder(); String[] vals = split(objectString, "."); for (int i=0; i<vals.length; i++){ val.append("." + vals[i]); result.append("!"+(val.substring(1))+"?'':"); } result.append(val.substring(1)); return result.toString(); -有了上面这些基础的东西,只需要在写一个控制层接口,就可以看到每次返回一个page对象,然后里面封装好了查询对象的列表,并且是按分页得出列表。
package com.store.controller; นำเข้า javax.servlet.http.httpservletrequest; นำเข้า Javax.servlet.http.httpservletResponse; import org.springframework.beans.factory.annotation.Autowired; นำเข้า org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.store.base.secondmodel.base.Page; import com.store.base.secondmodel.pratice.model.Product; import com.store.base.secondmodel.pratice.service.ProductService; /** *TODO *October 11, 2016*yiyong_wu */ @RestController @RequestMapping("/product") public class ProductController { @Autowired private ProductService productService; @ResponseBody @RequestMapping(value="/getPageProduct") public Page<Product> getPageProduct(HttpServletRequest request,HttpServletResponse response){ Page<Product> page = productService.findPage(new Page<Product>(request,response), new Product()); return page; -最后在看一下页面怎么使用这个page对象,这样我们就完整地介绍了这个一个分页功能,代码很多,但很完整。
<%@ page contentType="text/html;charset=UTF-8"%> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <html> <head> <title></title> <meta name="decorator" content="default" /> function page(n, s) { if (n) $("#pageNo").val(n); if (s) $("#pageSize").val(s); $("#searchForm").attr("action", "${ctx}/app/bank/list"); $("#searchForm").submit(); กลับเท็จ; } </script> </head> <body> <form:form id="searchForm" modelAttribute="XXXX" action="${ctx}/XXX" method="post"> <input id="pageNo" name="pageNo" type="hidden" value="${page.pageNo}" /> <input id="pageSize" name="pageSize" type="hidden" value="${page.pageSize}" /> <ul> <li> <label>Whether it is listed: </label> <form:select id="status" path="status"> <form:option value="" label=""/> <form:options items="${fns:getDictList('yes_no_app')}" itemLabel="label" itemValue="value" htmlEscape="false"/> </form:select> </li> <li><input id="btnSubmit" type="submit" value="query"/> <li></li> </ul> </form:form> <sys:message content="${message}" /> <sys:message content="${message}" /> <table id="contentTable"> <thead> <tr> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> </tr> </tbody> <c:forEach items="${page.list}" var="XXXX"> <tr> <td>${XXXX.name}</td> <td><a href="${ctx}/app/bank/form?id=${XXXX.id}">${XXXX.}</a></td> <td>${XXXX.}</td> <td>${XXXX.}</td> <td>${XXXX.}</td> <td>${fns:getDictLabel(XXXX.isHot, 'yes_no_app', 'no')}</td> <td>${XXXX.}</td> <td><c:if test="${XXXX.status==1 }">On the shelves</c:if> <c:if test="${XXXX.status==2 }">Off</c:if> </td> </td> </tr> </c:forEach> </tbody> </table> <div>${page} <li style="padding-top: 6px;padding-left: 12px;float: left;">Total ${page.count} </li></div> </body> </html>到这里就基本上把整个分页功能描述得比较清楚了,希望可以帮助到你们快速解决分页这个问题,当然要在前端显示分页漂亮的话要针对li做一些css样式啥的,最后祝福你可以快速掌握这个分页功能!
The above is the skills of the commonly used paging plug-in for Mybatis to implement quick paging. ฉันหวังว่ามันจะเป็นประโยชน์กับทุกคน หากคุณมีคำถามใด ๆ โปรดฝากข้อความถึงฉันและบรรณาธิการจะตอบกลับทุกคนในเวลา ขอบคุณมากสำหรับการสนับสนุนเว็บไซต์ Wulin.com!