1. 封装分页 Halaman 类
Paket com.framework.common.page.impl; import java.io.serializable; import com.framework.common.page.ipage;/** * * *//kelas abstrak publik Basepage mengimplementasikan iPage, serializable {/** */ private static final long serialversionuid = -362348612757790359l; public static int default_page_size = 20; private int pageSize = default_page_size; Private int CurrentResult; Totalpage int pribadi; private int currentpage = 1; private int totalCount = -1; Basepage publik (int currentPage, int pageSize, int totalCount) {this.currentpage = currentPage; this.pagesize = halaman; this.totalCount = TotalCount; } public int getTotalCount () {return this.totalCount; } public void setTotalCount (int totalCount) {if (totalCount <0) {this.totalCount = 0; kembali; } this.totalCount = TotalCount; } public basepage () {} public int getFirStresult () {return (this.currentpage - 1) * this.pagesize; } public void setPagesize (int pageSize) {if (pagesize <0) {this.pagesize = default_page_size; kembali; } this.pagesize = pageSize; } public int getTotalPage () {if (this.totalPage <= 0) {this.totalPage = (this.totalCount / this.pagesize); if ((this.totalPage == 0) || (this.totalCount % this.pagesize! = 0)) {this.totalPage += 1; }} return this.totalPage; } public int getPageSize () {return this.pagesize; } public void setPageno (int currentPage) {this.currentpage = currentPage; } public int getPageno () {return this.currentPage; } public boolean isFirstPage () {return this.currentPage <= 1; } public boolean isLastPage () {return this.currentPage> = getTotalPage (); } public int getNextPage () {if (isLastPage ()) {return this.currentPage; } return this.currentPage + 1; } public int getCurrentResult () {this.currentResult = ((getPageno () - 1) * getPageSize ()); if (this.currentResult <0) {this.currentResult = 0; } return this.currentResult; } public int getPrepage () {if (isFirstPage ()) {return this.currentPage; } return this.currentpage - 1; }}
Paket com.framework.common.page.impl; import java.util.list;/** * * * */halaman kelas publik memperluas basepage {/** * */private static final long serialversionuid = -970177928709377315l; Public Static Threadlocal <page> threadlocal = ThreadLocal baru <page> (); DAFTAR PRIBADI <?> Data; halaman publik () {} halaman publik (int currentpage, int pageSize, int totalCount) {super (lancar, halaman, totalcount); } halaman publik (int currentPage, int pageSize, int totalCount, daftar <?> data) {super (lancar, halaman, totalcount); this.data = data; } Daftar Publik <?> getData () {pengembalian data; } public void setData (Daftar <?> Data) {this.data = data; }}
2. 封装分页插件
Paket com.framework.common.page.plugin; impor java.sql.connection; impor java.sql.preparedstatement; impor java.sql.resultset; impor java.sql.sqlexception; impor java.util.list; impor java.util .Properties; impor javax.xml.bind.propertyexception; impor org.apache.commons.lang3.stringutils; impor org.apache.ibatis.executor.errorcontext; impor org.apache.ibatis.executor.executorexception; impor org.apache. iBatis.executor.statement.basestatementhandler; impor org.apache.iatis.executor.statement.routingstatementhandler; import org.apache.ibatis.mapping.boundsql; import org.apache.ibatis.mapping.mappedstatement; import org.apache.ibatis.mapping.mappedstatement; impor.apache.apache. pemetaan.parametermapping; import org.apache.atisis.mapping.parametermode; impor org.apache.atisis.plugin.interceptor; import org.apache.ibatis.plugin. .apache.ibatis.plugin.plugin; import org.apache.iathis.reflection.metaObject; impor org.apache.iatis.reflection.property.propertytokenizer; impor org.apache.atisis.scripting.xmltags.foreachsqlnode; .Ibatis.Session.onfigurasi; impor org.apache.ibatis.type.typehandler; impor org.apache.ibatis.type.typehandlerregistry; impor com.framework.common.page.impl.page; import com.framework.common.utils .Reflectutil;/** * * * */ @intercepts ({ @org.apache.iatis.plugin.Signature (type = org.apache.ibatis.executor.statement.statementhandler.class, method = "persiapkan", args = {Connection.class})}) kelas publik pageplugin mengimplementasikan interceptor {private string dialect = ""; private string pagesqlid = ""; @Override Public Object Intercept (Invocation Invocation) melempar Throwable {if (Invocation.getTarget () Instanceof RoutingStatementHandler) {BasestatementHandler delegate = (BasestatementHandler) Disploughate .GetValueFieldName ((RoutingStatementHandler) doa. MappedStatement MappedStatement = (MappedStatement) Reflectutil .GetValueByFieldName (Delegate, "MappedStatement"); Halaman halaman = page.threadlocal.get (); if (page == null) {page = halaman baru (); Page.threadlocal.set (halaman); } if (mappedStatement.getId (). cocok (".*(" + this.pagesqlid + ") $") && page.getPagesize ()> 0) {boundSQL BOODSQL = delegate.getBoundsql (); Objek parameterObject = boundsql.getParameterObject (); String sql = boundsql.getsql (); String countsqlid = mappedstatement.getId (). Replaceall (pagesqlid, "count"); MappedStatement CountMappedStatement = NULL; if (mappedstatement.getConfiguration (). hasstatement (countsqlid)) {countMappedStatement = mappedstatement.getConfiguration (). getMappedStatement (countsqlid); } String countsql = null; if (countmappedStatement! = null) {countsql = countmappedStatement.getBoundsql (parameterObject) .getSql (); } else {countsql = "pilih count (1) dari (" + sql + ") t_count"; } int totalCount = 0; Disiapkan countstmt = null; Hasil HasilSet = NULL; Coba {koneksi koneksi = (koneksi) Invocation.getArgs () [0]; countstmt = connection.preparestatement (countsql); BoundSQL CountBoundSQL = BoundSQL baru (MappedStatement.GetConfiguration (), CountSQL, BoundSQL.GetParametermappings (), ParameterObject); setParameters (countstmt, mappedstatement, countboundsql, parameterObject); hasil = countstmt.executeQuery (); if (resultet.next ()) {totalCount = resultet.getInt (1); }} catch (Exception e) {throw e; } akhirnya {coba {if (resultSet! = null) {resultet.close (); }} akhirnya {if (countstmt! = null) {countstmt.close (); }}} page.setTotalCount (totalCount); Reflectutil.setValueByFieldName (BoundSQL, "SQL", GeneratePagesQL (SQL, Page)); }} return Invocation.proed (); } / **? setParameters (disiapkan PS, pemetaan mappedstatement, boundsql boundsql, objek parameterObject) melempar sqlexception {errorContext.instance (). Activity ("Parameter Pengaturan"). Daftar <Parametermapping> parameterMappings = BoundSQL.GetParametermappings (); if (parameterMappings! = null) {configuration configuration = mappedstatement.getConfiguration (); TypeHandlerRegistry typeHandlerRegistry = configuration.gettypehandlerregistry (); MetaObject metaObject = parameterObject == null? null: configuration.newmetaObject (parameterObject); untuk (int i = 0; i <parametermappings.size (); i ++) {parametermapping parametermapping = parametermappings.get (i); if (parametermapping.getMode ()! = parametermode.out) {nilai objek; String propertyname = parametermapping.getProperty (); PropertyTokenizer prop = PropertyTokenizer baru (PropertiDyName); if (parameterObject == null) {value = null; } lain jika (typeHandlerregistry.hastypehandler (parameterObject.getClass ())) {value = parameterObject; } lain if (boundsql.hasAdditionalparameter (propertiyname)) {value = boundsql.getAdditionalparameter (propertieName); } lain if (propertyname.startswith (foreachsqlnode.item_prefix) && boundsql.hasadditionalparameter (prop.getName ())) {value = boundsql.getAdditionalparameter (prop.getName ()); if (value! = null) {value = configuration.newMetaObject (value) .getValue (propertiyname.substring (prop.getName (). length ())); }} else {value = metaObject == null? null: metaObject.getValue (propertieName); } TypeHandler typeHandler = parametermapping.gettypehandler (); if (typeHandler == null) {throw new ExecutOrException ("Tidak ada typeHandler yang ditemukan untuk parameter"+ propertiyname+ "dari pernyataan"+ mappedstatement.getId ()); } typeHandler.setParameter (ps, i + 1, value, parametermapping.getjdbctype ()); }}}} / ** * 根据数据库方言 , 生成特定的分页 sql * @param sql * @param halaman * @return * / string private GeneratePagesQl (string sql, halaman halaman) {if (halaman! = Null && stringutils. isNotBlank (dialek)) {stringBuffer pagesql = new StringBuffer (); if ("mysql" .equals (dialek)) {pagesql.append (sql); pagesql.append ("limit"+page.getCurrentResult ()+","+page.getPageSize ()); } lain jika ("oracle" .equals (dialek)) {pagesql.append ("pilih * dari (pilih tmp_tb. *, rownum row_id from ("); pagesql.append (sql); pagesql.append (") sebagai tmp_tb Di mana rownum <= "); pagesql.append (page.getCurrentResult ()+page.getPagesize ()); pagesql.append (") di mana row_id> "); pagesql.append (page.getCurrentResult ()); } return pagesql.toString (); } else {return sql; }} @Override Plugin objek publik (target objek) {return plugin.wrap (target, ini); } @Override public void setProperties (properti properti) {coba {if (stringutils.isempty (this.dialect = properties .getProperty ("Dialect"))) {throw new New PropertyException ("Properti dialek tidak ditemukan!"); } if (stringutils.isempty (this.pagesqlid = properties .getProperty ("pagesqlid"))) {throw new PropertyException ("Properti Pagesqlid tidak ditemukan!"); }} catch (PropertyException e) {E.PrintStackTrace (); }}}
3.Mybatis 配置文件: mybatis-config.xml
<? XML Versi = "1.0" encoding = "UTF-8"?> <! Doctype Configuration Public "-// mybatis.org//dtd sql peta config 3.0 // en" "http://mybatis.org/dtd /mybatis-3-config.dtd "> <configuration> <l plugins> <plugin interceptor =" com.framework.common.page.plugin.pageplugin "> <properti nama =" dialek "value =" mysql " /> <properti name = "pagesqlid" value = "bypage"/> </lugin> </lugin> </donfiguration>
4. 分页拦截器
Paket com.framework.common.page.interceptor; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; impor org.apache.commons.lang3.math.numberutils; impor org. .Modelandview; impor org.springframework.web.servlet.handler.handlerinterceptorAdapter; import com.framework.common.page.impl.page;/****14 **/kelas publik PageInterceptor memperluas handlerInterceptorAdapter {@override void void public Posthandle ( Permintaan httpservletRequest, respons httpservletResponse, penangan objek, modelAndView ModelAndView) melempar Exception {super.poSthandle (permintaan, respons, penangan, model danview); Halaman halaman = page.threadlocal.get (); if (halaman! = null) {request.setAttribute ("page", halaman); } Page.threadlocal.remove (); } @Override Public Boolean Prehandle (permintaan httpservletRequest, respons httpservletResponse, pawang objek) melempar pengecualian {string pageSize = request.getParameter ("pageSize"); String pageno = request.getParameter ("pageno"); Halaman halaman = halaman baru (); if (numberutils.isnumber (pagesize)) {page.setPagesize (numberutils.toint (pageSize)); } if (numberutils.isnumber (pageno)) {page.setPageno (numberutils.toint (pageno)); } Page.threadlocal.set (halaman); Kembali Benar; }}
5.spring 配置
<!- ================================================ ===================== - Muat file properti - ========================== ============================================= -> <Konteks: Properti -placeHolder Location = "classpath: application.properties" /> <bean id = "sqlSessionFactory"> <name properti = "DataSource" ref = "DataSource" /> <nama properti = "configLocation" value = "classPath: mybatis-config .xml "/> <name properti =" mapperlocations "> <cist> <value> classpath:/com/framework/mapper/**/*mapper.xml </ value> </list> </propert> </bean > <!- =============================================== ====================== - 通过扫描的模式 , 扫描目录下所有的 dao , 根据对应的 mapper.xml 为其生成代理类 - === ==================================================== ============== -> <bean id = "mapperscannerConfigurer"> <name properti = "basepackage" value = "com.framework.dao" /> <nama properti = "ProcessPropertyplaceHolders" value = "true" /> <name properti = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" /> </t bean>
6.SpringMVC 配置拦截器
<!-分页拦截器-> <bean id = "pageInterceptor"> </ bean> <!-配置拦截器-> <bean> <name properti = "interceptors"> <cist> <ref bean = "PageInterceptor"/> </list> </prop Property> </bean>