1.封装分页页类
软件包com.framework.common.page.impl; import java.io.serializable; import com.framework.common.page.ipage.ipage;/** * * * * */公共抽象类basepage basepage inpage ipage ipage,序列化{/** ** * */私有静态最终长序列化= -3623448612757790359L; public static int default_page_size = 20; private int pagesize = default_page_size;私人int CurrentResult;私人int总页; private int CurrentPage = 1; private int totalCount = -1; public Basepage(int CurrentPage,int PageSize,int totalCount){this.currentPage = CurrentPage; this.pagesize = pageize; this.totalCount = totalCount; } public int int getTotalCount(){返回this.totalCount; } public void settotalCount(int totalCount){if(totalCount <0){this.totalCount = 0;返回; } this.totalCount = totalCount; } public basepage(){} public int 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 int getTotalPage(){if(this.totalPage <= 0){this.totalPage =(this.totalCount / this.pagesize); if(((this.totalpage == 0)||(this.totalCount%this.pageize!= 0)){this.totalPage += 1; }}返回this.totalpage; } public int getPagesize(){返回this.pagesize; } public void setPageno(int CurrentPage){this.currentPage = CurrentPage; } public int getPageno(){返回this.currentPage; } public boolean isfirstpage(){返回this.currentPage <= 1; } public boolean islastPage(){返回this.currentPage> = getTotalPage(); } public int int getNextPage(){if(islastPage()){返回this.currentPage; }返回this.currentPage + 1; } public int int getCurrentResult(){this.currentResult =((getPageno() - 1) * getPagesize()); if(this.currentResult <0){this.currentResult = 0; }返回this.currentresult; } public int getPrepage(){if(isfirstpage()){return this.currentPage; }返回this.currentPage -1; }}}
软件包com.framework.common.page.impl; import java.util.list;/** * * * * */公共类页面扩展basepage {/** * */private static static final long serialversionUID = -97017779287093777315L; public static threadlocal <page> threadlocal = new threadlocal <page>();私人列表<?>数据; 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 = data; }公共列表<?> getData(){返回数据; } public void setData(list <?> data){this.data = data; }}}
2.封装分页插件
包com.framework.common.page.plugin; import java.sql.connection; import java.sql.preparedstatement; import java java.sql.Resultset; import java.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sql.sqlection; import java.util.util.util.util.util.import java.util.utiment; 。 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.ibate.ibatis.plugin.intercepts; import org.apache.apache.ibate.ibatis.ibatis.plugin.invocation; import; import; import; 。 。 。 {Connection.Class})})公共类PagePlugin实现Interceptor {private String silect =“”;私有字符串pagesqlid =“”; @Override public objoct Intercept(Invocation Invocation)抛出可投掷{if(Invocation.getTarget()instance of RoutingStatateMentHandler){basestatementHandler delegate =(basestatementhandler)Reflectutil .getValueByByBiffieldName(((reutingingStattatementHandler)Incocation.getTarget.getTarget figho示意图映射=(mappedstatement)反射ututil .getValuebyFieldName(委托,“映射statement”);页面= pag.threadlocal.get(); if(page == null){page = new page(); page.threadlocal.set(page); } if(mappedstatement.getId()。匹配(“。 object parameterObject = bundsql.getParameterObject();字符串sql = bundsql.getsql();字符串countsqlid = mappedstatement.getId()。替换(pagesqlid,“ count”);映射计数示意图= null; if(mappedstatement.getConfiguration()。hasStatement(countsqlid)){countmappedStatement = mappedstatement.getConfiguration()。getMappedStatement(countsqlid); }字符串countsql = null; if(countmappedstatement!= null){countsql = countmappedStatement.getBoundsql(parameterObject).getSql(); } else {countsql =“ select count(1)来自(“ + sql +”)t_count”; } int totalCount = 0;准备成立的countstmt = null; ResultSet Resultset = null;尝试{连接连接=(连接)Invocation.getArgs()[0]; countstmt = connection.preparestatement(countsql); boundsql countboundsql = new bundsql(mappedstatement.getConfiguration(),countsql,boundsql.getParamEtermAppings(),parameterObject); setParameters(countstmt,mappedStatement,countboundsql,parameterObject); resultset = countstmt.executequery(); if(resultset.next()){totalCount = resultset.getInt(1); }} catch(异常E){throw e; }最后{尝试{if(resultset!= null){resultset.close(); }}最后{if(countstmt!= null){countstmt.close(); }}} page.setTotAlCount(totalCount); ReflectUtil.SetValuebyFieldName(boundsql,“ sql”,generatePagesql(sql,page)); }} return Invocation.proceed(); } / ** *对s sql参数(?)设值,参考org.apache.ibatis.executor.parameter.defaultParameter.defaultParameterHandler * @param ps * @param mappedstatement * @param bundsql * @param bundsql * @param parameterobject * setParameters(准备成员PS,示意图示意图,boundsql bungsql,object parameterObject)抛出sqlexception {errorcontext.instance()。活动(“设置参数”(“设置参数”)。object(mappedstatement.getParameTermap(mappedstatement.getParametermap() list <parametermapping> 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 ++){parametermapping parametermapping = parametermappings.get(i); if(parametermapping.getMode()!= parametermode.out){对象值;字符串propertyName = parametermapping.getProperty(); PropertyTokenizer Prop = new PropertyTokenizer(propertyName); if(parameterObject == null){value = null; } else if(typeHandlerRegistry.hastypeHandler(parameterobject.getClass())){value = parameterObject; } else if(bundsql.hasadditionalParameter(propertyName)){value = boundsql.getAdditionalParameter(propertyName); } else if(propertyName.startswith(foreachsqlnode.item_prefix)&& boundsql.hasadditionalParameter(prop.getName())){value = boundsql.getSql.getAdditionalParameter(prop.getName()); if(value!= null){value = configuration.newMetaObject(value).getValue(propertyName.Substring(prop.getName()。lentht())); }} else {value = metaObject == null? null:metaObject.getValue(propertyName); } typeHandler typehandler = parametermapping.getTypeHandler(); if(typeHandler == null){抛出新的executorexception(“没有为参数“+ propertyname+” of语句“+ mappedstatement.getId()); } typeHandler.setParameter(ps,i + 1,value,parametermapping.getJdbctype()); }}}}} / ** *根据数据库方言,sql * @param sql * @param page * @return * @return * / private string gentratePagesql(String sql,sql,page){if(page!= null && stringutils。 isNotblank(arilect)){StringBuffer Pagesql = new StringBuffer(); if(“ mysql” .equals(arilect)){pagesql.append(sql); pagesql.append(“ limit”+page.getCurrentResult()+“,”+page.getPagesize()); } else if(“ oracle” .equals(arilect)){pagesql.append(“ select * from(select tmp_tb。其中rownum <=“); pagesql.append(page.getCurrentResult()+page.getPagesize()); pagesql.append(“)whene row_id>”); pagesql.append(page.getCurrentResult()); } return pagesql.tostring(); } else {return sql; }} @Override公共对象插件(对象目标){return plugin.wrap(target,this); } @Override public void setProperties(属性属性){尝试{if(strignutils.isementy(this.dialect = properties .getProperty(“ dialect”))){thor new properteTexception(未找到方言属性! } if(strignutils.isempty(this.pagesqlid = properties .getProperty(“ pagesqlid''))){抛出新的propertyException(“找不到pagesqlid属性!”); }} catch(propertyException e){e.printstacktrace(); }}}}
3.Mybatis配置文件:mybatis-config.xml
<?xml版本=“ 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> <plugins> <插件name =“ pagesqlid” value =“ bypage”/> </> </plugin> </plugins> </configuration>
4.分页拦截器
package com.framework.common.page.interceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.lang3.math.NumberUtils;import org.springframework.web.servlet 。 httpservletrequest请求,httpservletresponse响应,对象处理程序,modelAndView modelAndView)抛出异常{super.posthandle(请求,响应,handler,handler,modelandview);页面= pag.threadlocal.get(); if(page!= null){request.setAttribute(“ page”,page); } page.threadlocal.remove(); } @Override public boolean prehandle(httpservletrequest请求,httpservletresponse响应,对象处理程序)抛出异常{string pagesize = request.getParameter(“ pagesize”);字符串pageno = request.getParameter(“ pageno”);页面= new page(); if(numberutils.isnumber(pagesize)){page.setPagesize(numberutils.toint(pagesize)); } if(numberutils.isnumber(pageno)){page.setPageno(numberutils.toint(pageno)); } page.threadlocal.set(page);返回true; }}}
5.春季
<! - ============================================ =================== - 加载属性文件 - ====================================== ======================================= - > <contest:context:property -placeholder location =“ classpath:applicat.properties” /> <bean id =“ sqlsessionfactory”> <property name =“ dataSource” ref =“ dataSource” /> <property name =“ configLocation” value =“ class path:mybatis-config 。 > <! - ========================================= ====================== - 通过扫描的模式=============================================== ============= - > <bean ID =“ mapperscannerconfigurer”> <property name =“ basepackage” value =“ com.framework.dao” /> <property name =“ ProcessPropertyPlaceholders” value =“ true” /> <属性名称=“ sqlsessionfactorybeanname” value =“ sqlsessionfactory” /> < /bean>
6.springmvc配置拦截器
态“ pageInterceptor”/> </list> </property> </bean>