1. 封装分页 페이지 类
package com.framework.common.page.impl; import java.io.serializable; import com.framework.common.page.ipage;/** * * */public basepage empage empage, serializable {/** * */ 개인 정적 최종 최종 긴 SerialVersionUID = -3623448612757790359L; public static int default_page_size = 20; private int pagesize = default_page_size; 개인 int currentResult; 개인 int totalpage; 개인 int currentPage = 1; 개인 int totalcount = -1; public basepage (int currentpage, int pagesize, int totalcount) {this.currentpage = currentpage; this.pagesize = pagesize; this.totalCount = TotalCount; } public int getTotalCount () {return this.totalCount; } public void settoTalCount (int totalCount) {if (totalCount <0) {this.totalCount = 0; 반품; } 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; 반품; } 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 ()) {reture this.currentPage; } reture 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 ()) {reture this.currentPage; } return this.currentPage -1; }}
package com.framework.common.page.impl; import java.util.list;/** * * */public class page 확장 기준 {/** */private static final long serialversionuid = -97017928709377315L; public static strandlocal <페이지> threadlocal = new ThreadLocal <페이지> (); 개인 목록 <?> 데이터; public page () {} public page (int currentpage, int pagesize, int totalcount) {super (currentpage, pagesize, totalcount); } public page (int currentpage, int pagesize, int totalcount, list <?> data) {super (currentPage, pagesize, totalCount); this.data = 데이터; } public list <?> getData () {return data; } public void setData (list <?> data) {this.data = data; }}
2. 封装分页插件
package com.framework.common.page.plugin; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultset; import java.sql.sqlexception; import java.util.list; import java.util .properties; import javax.xml.bind.properneexception; import org.apache.commons.lang3.stringutils; import org.apache.ibatis.executor.errorcontext; import org.apache.ibatis.executor.executorexception; import org.apache. IBATIS.Executor.statement.basestatementHandler; import org.apache.ibatis.executor.statement.routingstatementhandler; import org.apache.ibatis.mapping.boundsql; import org.apache.ibatis.mapping.mappedstatement; import org.apache.ibatis. Mapping.parameterMpapping; import org.apache.ibatis.mapping.parametermode; import org.apache.ibatis.plugin.interceptor; import org.apache.ibatis.plugin.intercepts; import org.apache.ibatis.plugin.invocation; import org .apache.ibatis.plugin.plugin; import org.apache.ibatis.reflection.metaobject; import org.apache.ibatis.reflection.property.propertytokenizer; import org.apache.ibatis.scripting.xmltags.foreachsqlnode; import org.apache .ibatis.session.configuration; import org.apache.ibatis.type.typehandler; import org.apache.ibatis.type.typehandlerregistry; import com.framework.common.page.impl.page; import com.framework.common.utils .reflectUtil;/** * * * */ @intercepts ({ @org.apache.ibatis.plugin.signature (type = org.apache.ibatis.executor.statement.statementhandler.class, method = "rade", args = {connection.class})}) public class pageplugin은 인터셉터 {private String dialect = ""; 개인 문자열 pagesqlid = ""; @override public object intercept (호출 호출) 던지기 가능 {if (invocation.getTarget () RoutingStatementHandler 인스턴스 인스턴스) {BasestatementHandler delegate = (basestatementHandler) refultUtil .getValueByfieldName ((RoutingStatementHandler) revAction.getTarget (), "delegate"); MappedStatement MAPPEDSTATEMENT = (MAPPEDSTATEMENT) RELFICUTIL .GetValueByfieldName (Delegate, "MappedStatement"); 페이지 페이지 = page.threadlocal.get (); if (page == null) { page = new Page(); page.threadlocal.set (페이지); } if (mappedStatement.getId (). matches ( ".*(" + this.pagesqlid + ") $") && page.getPagesize ()> 0) {boundsql boundsql = delegate.getBoundSql (); Object ParameterObject = boundsql.getParameterObject (); 문자열 sql = boundsql.getSql (); 문자열 countsqlid = mappedstatement.getId (). replaceall (pagesqlid, "count"); MAPPEDSTATEMENT COUNTMAPPEDSTATEMENT = NULL; if (mappedStatement.getConfiguration (). hasstatement (countsqlid)) {countMappedStatement = MappedStatement.getConfiguration (). GetMappedStatement (COUNTSQLID); } 문자열 countsql = null; if (countMappedStatement! = null) {countsql = countmappedStatement.getBoundSql (ParameterObject) .getSql (); } else {countsql = "count (1)에서 (" + sql + ") t_count"; } int totalcount = 0; 준비 상태 COUNTSTMT = NULL; resultSet resultSet = null; {Connection Connection = (Connection) invocation.getArgs () [0]; countstmt = connection.preparestatement (countsql); BONDSQL COUNTBOUNDSQL = NEW BONDSQL (MAPPEDSTATEMENT.GETCONFIGURATION (), COUNTSQL, BONDSQL.GETPARAMETERMAPPINGS (), PARAMETEROBJECT); setParameters (CountStmt, MappedStatement, CountBoundSql, ParameterObject); resultSet = countstmt.executeQuery (); if (resultSet.next ()) {TotalCount = resultSet.getInt (1); }} catch (예외 e) {throw e; } 마침내 {try {if (resultSet! = null) {resultSet.close (); }} 마침내 {if (countStmt! = null) {countStmt.close (); }}} page.setTotalCount (TotalCount); recelsUtil.setValueByfieldName (boundsql, "sql", generatepagesql (sql, page)); }} return invocation.proceed (); } / ** * * sql 参数 (?) 设值 设值, 参考 org.apache.ibatis.executor.parameter.defaultParameterAndler * @param ps * @param mappedstatement * @param boundsql * @param parameterObject * @throws sqlexcection * / private void setParameters (preadStatement ps, MappedStatement MappedStatement, boundsql boundsql, Object ParameterObject)는 sqlexception {errorcontext.instance () activity ( "설정 매개 변수"). 개체 (mappedStatement.getParameterMap (). getId ()); List <ParametErmpaping> ParametErmappings = boundsql.getParameterMappings (); if (parameterMappings! = null) {configuration configuration = mappedStatement.getConfiguration (); TypeHandlerRegistry TypeHandlerRegistry = configuration.getTypeHandlerRegistry (); metaobject metaobject = parameterObject == null? null: configuration.newMetaObject(parameterObject); for (int i = 0; i <parameterMappings.size (); i ++) {ParametErmpapping ParametErmpaping = ParameterMappings.get (i); if (parameterMpapping.getMode ()! = ParametErmode.out) {개체 값; 문자열 propertyname = parameterMpapp.GetProperty (); PropertyTokenizer Prop = New PropertyTokenizer (PropertyName); if (parameterObject == null) {value = null; } else if (typeHandlerRegistry.hastypeHandler (parameterObject.getClass ())) {value = parameterObject; } else if (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 (). longth ())); }} else {value = metaobject == null? null : metaobject.getValue (PropertyName); } TypeHandler TypeHandler = ParametErmpapp.GetTypeHandler (); if (typehandler == null) {Throw new executeRexception ( "매개 변수에 대한 유형 핸들러가 없음"+ propertyName+ "명령문"+ mappedStatement.getId ()); } typeHandler.setParameter (ps, i + 1, 값, parameterMpapp.getJdbCtype ()); }}}}}} / ** * 根据数据库方言 根据数据库方言, 生成特定的分页 sql * @param sql * @param page * @return * / private string generatepagesql (string sql, page page) {if (page! = null && stringUtils. ISNOTBLANK (dialect)) {StringBuffer pagesql = new StringBuffer (); if ( "mysql".equals (dialect)) {pagesql.append (sql); pagesql.append ( "limit"+page.getCurrentResult ()+","+page.getPagesize ()); } else if ( "Oracle".Equals (dialect)) {pagesql.append ( "select * from (select tmp_tb. *, rownum row_id from ("); pagesql.append (sql); pagesql.append ( ") as tmp_tb 여기서 rownum <= "); pagesql.append (page.getCurrentResult ()+page.getPagesize ()); pagesql.append (") where row_id> "); pagesql.append (page.getCurrentResult ()); } return pagesql.toString (); } else {return sql; }} @override public Object Plugin (개체 대상) {return plugin.wrap (target, this); } @Override public void setProperties (속성 속성) {try {if (stringUtils.isempty (this.Dialect = 속성 .getProperty ( "dialect"))) {Throw New PropertyException ( "Dialect 속성을 찾을 수 없습니다!"); } if (stringUtils.isempty (this.pagesqlid = properties .getProperty ( "pagesqlid")))) {Throw New PropertyException ( "pagesqlid 속성을 찾을 수 없습니다!"); }} catch (PropertyException e) {e.printstacktrace (); }}}
3. Mybatis is : mybatis-config.xml
<? xml version = "1.0"encoding = "utf-8"?> <! doctype configuration public "-// mybatis.org//dtd sql map config 3.0 // en" "http://mybatis.org/dtd /mybatis-3-config.dtd "> <configuration> <플러그인> <플러그인 interceptor ="com.framework.common.page.plugin.pageplugin "> <property name ="dialect "value ="mysql " /> <속성 이름 = "pagesqlid"value = "bypage"/> </plugin> </plugins> </configuration>
4. 分页拦截器
package com.framework.common.page.interceptor; import javax.servlet.http.httpervletrequest; import javax.servlet.http.httpervletresponse; import org.apache.commons.lang3.math.numberutils; import org.springfrffework.web.servert .ModelandView; import org.springframework.web.servlet.handler.handlerinterceptoradapter; import com.framework.common.page.impl.page;/****14 **/public class pageinterceptor 확장 핸들러 inceptoradapter (@override public void posthandle) httpservletrequest 요청, httpservletresponse 응답, 객체 핸들러, ModelandView ModelandView)는 예외 {super.posthandle (요청, 응답, 핸들러, ModelAndView); 페이지 페이지 = page.threadlocal.get (); if (page! = null) {request.setattribute ( "page", page); } page.threadlocal.remove (); } @override public boolean prehandle (httpservletrequest request, httpservletresponse 응답, 객체 핸들러) 예외 {string pagesize = request.getParameter ( "pagesize"); 문자열 pageno = request.getParameter ( "pageno"); 페이지 페이지 = 새 페이지 (); if (numberutils.isnumber (pagesize)) {page.setpagesize (numberutils.toint (pagesize)); } if (numberUtils.isNumber (pageno)) {page.setpageno (numberutils.toint (pageno)); } page.threadlocal.set (페이지); 진실을 반환하십시오. }}
5. 스프링 配置
<!- ============================================== ======================- 부드러운 속성 파일 - ========================= ============================================ -> <문맥 : 속성 -placeholder location = "classpath.properties" /> <bean id = "sqlsessionFactory"> <property name = "dataSource"ref = "dataSource" /> <property name = "configlocation"value = "classpath : mybatis-config .xml "/> <property name ="mapperlocations "> <list> <list> value> classpath :/com/framework/mapper/**/*mapper.xml </value> </list> </property> </bean > <!- ============================================= = 일반 =================================================== =============== -> <bean id = "mapperscannerConfigurer"> <property name = "basePackage"value = "com.framework.dao" /> <property name = "processPropertyplaceholders" value = "true" /> <property name = "sqlsessionfactorybeanname"value = "sqlsessionfactory" /> < /bean>
6.springmvc 配置拦截器
<!->-> <bean id = "pageinterceptor"> </bean> <!-配置拦截器-> <ean> <속성 이름 = "interceptors"> <list> <Ref bean = "PageInterceptor"/> </list> </property> </bean>