欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Mybatis常用分頁(yè)插件實(shí)現(xiàn)快速分頁(yè)處理技巧

 更新時(shí)間:2016年10月14日 09:13:25   作者:yy_308_sy  
這篇文章主要介紹了Mybatis常用分頁(yè)插件實(shí)現(xiàn)快速分頁(yè)處理的方法。非常不錯(cuò)具有參考借鑒價(jià)值,感興趣的朋友一起看看

在未分享整個(gè)查詢(xún)分頁(yè)的執(zhí)行代碼之前,先了解一下執(zhí)行流程。

1.總體上是利用mybatis的插件攔截器,在sql執(zhí)行之前攔截,為查詢(xún)語(yǔ)句加上limit X X

2.用一個(gè)Page對(duì)象,貫穿整個(gè)執(zhí)行流程,這個(gè)Page對(duì)象需要用Java編寫(xiě)前端分頁(yè)組件

3.用一套比較完整的三層entity,dao,service支持這個(gè)分頁(yè)架構(gòu)

4.這個(gè)分頁(yè)用到的一些輔助類(lèi)

注:分享的內(nèi)容較多,這邊的話我就不把需要的jar一一列舉,大家使用這個(gè)分頁(yè)功能的時(shí)候缺少什么就去晚上找什么jar包即可,盡可能用maven包導(dǎo)入因?yàn)閙aven能減少版本沖突等比較好的優(yōu)勢(shì)。

我只能說(shuō)盡可能讓大家快速使用這個(gè)比較好用的分頁(yè)功能,如果講得不明白,歡迎加我QQ一起探討1063150576,。莫噴哈!還有就是文章篇幅可能會(huì)比較大,不過(guò)花點(diǎn)時(shí)間,把它看完并實(shí)踐一下一定會(huì)收獲良多。

第一步:既然主題是圍繞怎么進(jìn)行分頁(yè)的,我們就從mybatis入手,首先,我們把mybatis相關(guān)的兩個(gè)比較重要的配置文件拿出來(lái)做簡(jiǎn)要的理解,一個(gè)是mybatis-config.xml,另外一個(gè)是實(shí)體所對(duì)應(yīng)的mapper配置文件,我會(huì)在配置文件上寫(xiě)好注釋?zhuān)蠹乙豢淳蜁?huì)明白。

mybatis-config.xml

<!DOCTYPE configuration 
PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration> 
<!-- 全局參數(shù) --> 
<settings> 
<!-- 使全局的映射器啟用或禁用緩存。 --> 
<setting name="cacheEnabled" value="false"/> 
<!-- 全局啟用或禁用延遲加載。當(dāng)禁用時(shí),所有關(guān)聯(lián)對(duì)象都會(huì)即時(shí)加載。 --> 
<setting name="lazyLoadingEnabled" value="true"/> 
<!-- 當(dāng)啟用時(shí),有延遲加載屬性的對(duì)象在被調(diào)用時(shí)將會(huì)完全加載任意屬性。否則,每種屬性將會(huì)按需要加載。 --> 
<setting name="aggressiveLazyLoading" value="true"/> 
<!-- 是否允許單條sql 返回多個(gè)數(shù)據(jù)集 (取決于驅(qū)動(dòng)的兼容性) default:true --> 
<setting name="multipleResultSetsEnabled" value="true"/> 
<!-- 是否可以使用列的別名 (取決于驅(qū)動(dòng)的兼容性) default:true --> 
<setting name="useColumnLabel" value="true"/> 
<!-- 允許JDBC 生成主鍵。需要驅(qū)動(dòng)器支持。如果設(shè)為了true,這個(gè)設(shè)置將強(qiáng)制使用被生成的主鍵,有一些驅(qū)動(dòng)器不兼容不過(guò)仍然可以執(zhí)行。 default:false --> 
<setting name="useGeneratedKeys" value="false"/> 
<!-- 指定 MyBatis 如何自動(dòng)映射 數(shù)據(jù)基表的列 NONE:不隱射 PARTIAL:部分 FULL:全部 --> 
<setting name="autoMappingBehavior" value="PARTIAL"/> 
<!-- 這是默認(rèn)的執(zhí)行類(lèi)型 (SIMPLE: 簡(jiǎn)單; REUSE: 執(zhí)行器可能重復(fù)使用prepared statements語(yǔ)句;BATCH: 執(zhí)行器可以重復(fù)執(zhí)行語(yǔ)句和批量更新) --> 
<setting name="defaultExecutorType" value="SIMPLE"/> 
<!-- 使用駝峰命名法轉(zhuǎn)換字段。 --> 
<setting name="mapUnderscoreToCamelCase" value="true"/> 
<!-- 設(shè)置本地緩存范圍 session:就會(huì)有數(shù)據(jù)的共享 statement:語(yǔ)句范圍 (這樣就不會(huì)有數(shù)據(jù)的共享 ) defalut:session --> 
<setting name="localCacheScope" value="SESSION"/> 
<!-- 設(shè)置但JDBC類(lèi)型為空時(shí),某些驅(qū)動(dòng)程序 要指定值,default:OTHER,插入空值時(shí)不需要指定類(lèi)型 --> 
<setting name="jdbcTypeForNull" value="NULL"/> 
<setting name="logPrefix" value="dao."/> 
</settings> 
<!--別名是一個(gè)較短的Java 類(lèi)型的名稱(chēng) --> 
<typeAliases> 
<typeAlias type="com.store.base.model.StoreUser" 
alias="User"></typeAlias> 
<typeAlias type="com.store.base.secondmodel.pratice.model.Product" 
alias="Product"></typeAlias> 
<typeAlias type="com.store.base.secondmodel.base.Page" 
alias="Page"></typeAlias> 
</typeAliases> 
<!-- 插件配置,這邊為mybatis配置分頁(yè)攔截器,這個(gè)分頁(yè)攔截器需要我們自己實(shí)現(xiàn) --> 
<plugins> 
<plugin interceptor="com.store.base.secondmodel.base.pageinterceptor.PaginationInterceptor" /> 
</plugins> 
</configuration>

一個(gè)ProductMapper.xml作為測(cè)試對(duì)象,這個(gè)mapper文件就簡(jiǎn)單配置一個(gè)需要用到的查詢(xún)語(yǔ)句

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 
<mapper namespace="com.store.base.secondmodel.pratice.dao.ProductDao" > 
<sql id="baseColumns" > 
id, product_name as productName, product_no as productNo, price as price 
</sql> 
<select id="findList" resultType="com.store.base.secondmodel.pratice.model.Product"> 
select <include refid="baseColumns"/> from t_store_product 
</select> 
</mapper>

第二步:接下去主要針對(duì)這個(gè)分頁(yè)攔截器進(jìn)行深入分析學(xué)習(xí),主要有以下幾個(gè)類(lèi)和其對(duì)應(yīng)接口

(1)BaseInterceptor 攔截器基礎(chǔ)類(lèi)

(2)PaginationInterceptor 我們要使用的分頁(yè)插件類(lèi),繼承上面基礎(chǔ)類(lèi)

(3)SQLHelper 主要是用來(lái)提前執(zhí)行count語(yǔ)句,還有就是獲取整個(gè)完整的分頁(yè)語(yǔ)句

(4)Dialect,MysqlDialect,主要用來(lái)數(shù)據(jù)庫(kù)是否支持limit語(yǔ)句,然后封裝完整limit語(yǔ)句

以下是這幾個(gè)類(lèi)的分享展示

BaseInterceptor.java

package com.store.base.secondmodel.base.pageinterceptor; 
import java.io.Serializable; 
import java.util.Properties; 
import org.apache.ibatis.logging.Log; 
import org.apache.ibatis.logging.LogFactory; 
import org.apache.ibatis.plugin.Interceptor; 
import com.store.base.secondmodel.base.Global; 
import com.store.base.secondmodel.base.Page; 
import com.store.base.secondmodel.base.dialect.Dialect; 
import com.store.base.secondmodel.base.dialect.MySQLDialect; 
import com.store.base.util.Reflections; 
/** 
* Mybatis分頁(yè)攔截器基類(lèi) 
* @author yiyong_wu 
* 
*/ 
public abstract class BaseInterceptor implements Interceptor, Serializable { 
private static final long serialVersionUID = 1L; 
protected static final String PAGE = "page"; 
protected static final String DELEGATE = "delegate"; 
protected static final String MAPPED_STATEMENT = "mappedStatement"; 
protected Log log = LogFactory.getLog(this.getClass()); 
protected Dialect DIALECT; 
/** 
* 對(duì)參數(shù)進(jìn)行轉(zhuǎn)換和檢查 
* @param parameterObject 參數(shù)對(duì)象 
* @param page 分頁(yè)對(duì)象 
* @return 分頁(yè)對(duì)象 
* @throws NoSuchFieldException 無(wú)法找到參數(shù) 
*/ 
@SuppressWarnings("unchecked") 
protected static Page<Object> convertParameter(Object parameterObject, Page<Object> page) { 
try{ 
if (parameterObject instanceof Page) { 
return (Page<Object>) parameterObject; 
} else { 
return (Page<Object>)Reflections.getFieldValue(parameterObject, PAGE); 
} 
}catch (Exception e) { 
return null; 
} 
} 
/** 
* 設(shè)置屬性,支持自定義方言類(lèi)和制定數(shù)據(jù)庫(kù)的方式 
* <code>dialectClass</code>,自定義方言類(lèi)??梢圆慌渲眠@項(xiàng) 
* <ode>dbms</ode> 數(shù)據(jù)庫(kù)類(lèi)型,插件支持的數(shù)據(jù)庫(kù) 
* <code>sqlPattern</code> 需要攔截的SQL ID 
* @param p 屬性 
*/ 
protected void initProperties(Properties p) { 
Dialect dialect = null; 
String dbType = Global.getConfig("jdbc.type"); 
if("mysql".equals(dbType)){ 
dialect = new MySQLDialect(); 
} 
if (dialect == null) { 
throw new RuntimeException("mybatis dialect error."); 
} 
DIALECT = dialect; 
} 
}

PaginationInterceptor.java

package com.store.base.secondmodel.base.pageinterceptor; 
import java.util.Properties; 
import org.apache.ibatis.executor.Executor; 
import org.apache.ibatis.mapping.BoundSql; 
import org.apache.ibatis.mapping.MappedStatement; 
import org.apache.ibatis.mapping.SqlSource; 
import org.apache.ibatis.plugin.Intercepts; 
import org.apache.ibatis.plugin.Invocation; 
import org.apache.ibatis.plugin.Plugin; 
import org.apache.ibatis.plugin.Signature; 
import org.apache.ibatis.reflection.MetaObject; 
import org.apache.ibatis.session.ResultHandler; 
import org.apache.ibatis.session.RowBounds; 
import com.store.base.secondmodel.base.Page; 
import com.store.base.secondmodel.base.util.StringUtils; 
import com.store.base.util.Reflections; 
/** 
* 數(shù)據(jù)庫(kù)分頁(yè)插件,只攔截查詢(xún)語(yǔ)句. 
* @author yiyong_wu 
* 
*/ 
@Intercepts({ @Signature(type = Executor.class, method = "query", args = { 
MappedStatement.class, Object.class, RowBounds.class, 
ResultHandler.class }) }) 
public class PaginationInterceptor extends BaseInterceptor { 
private static final long serialVersionUID = 1L; 
@Override 
public Object intercept(Invocation invocation) throws Throwable { 
final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; 
Object parameter = invocation.getArgs()[1]; 
BoundSql boundSql = mappedStatement.getBoundSql(parameter); 
Object parameterObject = boundSql.getParameterObject(); 
// 獲取分頁(yè)參數(shù)對(duì)象 
Page<Object> page = null; 
if (parameterObject != null) { 
page = convertParameter(parameterObject, page); 
} 
// 如果設(shè)置了分頁(yè)對(duì)象,則進(jìn)行分頁(yè) 
if (page != null && page.getPageSize() != -1) { 
if (StringUtils.isBlank(boundSql.getSql())) { 
return null; 
} 
String originalSql = boundSql.getSql().trim(); 
// 得到總記錄數(shù) 
page.setCount(SQLHelper.getCount(originalSql, null,mappedStatement, parameterObject, boundSql, log)); 
// 分頁(yè)查詢(xún) 本地化對(duì)象 修改數(shù)據(jù)庫(kù)注意修改實(shí)現(xiàn) 
String pageSql = SQLHelper.generatePageSql(originalSql, page,DIALECT); 
invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET,RowBounds.NO_ROW_LIMIT); 
BoundSql newBoundSql = new BoundSql( 
mappedStatement.getConfiguration(), pageSql, 
boundSql.getParameterMappings(), 
boundSql.getParameterObject()); 
// 解決MyBatis 分頁(yè)foreach 參數(shù)失效 start 
if (Reflections.getFieldValue(boundSql, "metaParameters") != null) { 
MetaObject mo = (MetaObject) Reflections.getFieldValue( 
boundSql, "metaParameters"); 
Reflections.setFieldValue(newBoundSql, "metaParameters", mo); 
} 
// 解決MyBatis 分頁(yè)foreach 參數(shù)失效 end 
MappedStatement newMs = copyFromMappedStatement(mappedStatement,new BoundSqlSqlSource(newBoundSql)); 
invocation.getArgs()[0] = newMs; 
} 
return invocation.proceed(); 
} 
@Override 
public Object plugin(Object target) { 
return Plugin.wrap(target, this); 
} 
@Override 
public void setProperties(Properties properties) { 
super.initProperties(properties); 
} 
private MappedStatement copyFromMappedStatement(MappedStatement ms, 
SqlSource newSqlSource) { 
MappedStatement.Builder builder = new MappedStatement.Builder( 
ms.getConfiguration(), ms.getId(), newSqlSource, 
ms.getSqlCommandType()); 
builder.resource(ms.getResource()); 
builder.fetchSize(ms.getFetchSize()); 
builder.statementType(ms.getStatementType()); 
builder.keyGenerator(ms.getKeyGenerator()); 
if (ms.getKeyProperties() != null) { 
for (String 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 implements SqlSource { 
BoundSql boundSql; 
public BoundSqlSqlSource(BoundSql boundSql) { 
this.boundSql = boundSql; 
} 
@Override 
public BoundSql getBoundSql(Object parameterObject) { 
return boundSql; 
} 
} 
}

SQLHelper.java

package com.store.base.secondmodel.base.pageinterceptor; 
import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.List; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import org.apache.ibatis.executor.ErrorContext; 
import org.apache.ibatis.executor.ExecutorException; 
import org.apache.ibatis.logging.Log; 
import org.apache.ibatis.mapping.BoundSql; 
import org.apache.ibatis.mapping.MappedStatement; 
import org.apache.ibatis.mapping.ParameterMapping; 
import org.apache.ibatis.mapping.ParameterMode; 
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.store.base.secondmodel.base.Global; 
import com.store.base.secondmodel.base.Page; 
import com.store.base.secondmodel.base.dialect.Dialect; 
import com.store.base.secondmodel.base.util.StringUtils; 
import com.store.base.util.Reflections; 
/** 
* SQL工具類(lèi) 
* @author yiyong_wu 
* 
*/ 
public class SQLHelper { 
/** 
* 默認(rèn)私有構(gòu)造函數(shù) 
*/ 
private SQLHelper() { 
} 
/** 
* 對(duì)SQL參數(shù)(?)設(shè)值,參考o(jì)rg.apache.ibatis.executor.parameter.DefaultParameterHandler 
* 
* @param ps 表示預(yù)編譯的 SQL 語(yǔ)句的對(duì)象。 
* @param mappedStatement MappedStatement 
* @param boundSql SQL 
* @param parameterObject 參數(shù)對(duì)象 
* @throws java.sql.SQLException 數(shù)據(jù)庫(kù)異常 
*/ 
@SuppressWarnings("unchecked") 
public static void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException { 
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId()); 
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) { 
Object value; 
String propertyName = parameterMapping.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().length())); 
} 
} else { 
value = metaObject == null ? null : metaObject.getValue(propertyName); 
} 
@SuppressWarnings("rawtypes") 
TypeHandler typeHandler = parameterMapping.getTypeHandler(); 
if (typeHandler == null) { 
throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId()); 
} 
typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType()); 
} 
} 
} 
} 
/** 
* 查詢(xún)總紀(jì)錄數(shù) 
* @param sql SQL語(yǔ)句 
* @param connection 數(shù)據(jù)庫(kù)連接 
* @param mappedStatement mapped 
* @param parameterObject 參數(shù) 
* @param boundSql boundSql 
* @return 總記錄數(shù) 
* @throws SQLException sql查詢(xún)錯(cuò)誤 
*/ 
public static int getCount(final String sql, final Connection connection, 
final MappedStatement mappedStatement, final Object parameterObject, 
final BoundSql boundSql, Log log) throws SQLException { 
String dbName = Global.getConfig("jdbc.type"); 
final String countSql; 
if("oracle".equals(dbName)){ 
countSql = "select count(1) from (" + sql + ") tmp_count"; 
}else{ 
countSql = "select count(1) from (" + removeOrders(sql) + ") tmp_count"; 
} 
Connection conn = connection; 
PreparedStatement ps = null; 
ResultSet rs = null; 
try { 
if (log.isDebugEnabled()) { 
log.debug("COUNT SQL: " + StringUtils.replaceEach(countSql, new String[]{"\n","\t"}, new String[]{" "," "})); 
} 
if (conn == null){ 
conn = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection(); 
} 
ps = conn.prepareStatement(countSql); 
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql, 
boundSql.getParameterMappings(), parameterObject); 
//解決MyBatis 分頁(yè)foreach 參數(shù)失效 start 
if (Reflections.getFieldValue(boundSql, "metaParameters") != null) { 
MetaObject mo = (MetaObject) Reflections.getFieldValue(boundSql, "metaParameters"); 
Reflections.setFieldValue(countBS, "metaParameters", mo); 
} 
//解決MyBatis 分頁(yè)foreach 參數(shù)失效 end 
SQLHelper.setParameters(ps, mappedStatement, countBS, parameterObject); 
rs = ps.executeQuery(); 
int count = 0; 
if (rs.next()) { 
count = rs.getInt(1); 
} 
return count; 
} finally { 
if (rs != null) { 
rs.close(); 
} 
if (ps != null) { 
ps.close(); 
} 
if (conn != null) { 
conn.close(); 
} 
} 
} 
/** 
* 根據(jù)數(shù)據(jù)庫(kù)方言,生成特定的分頁(yè)sql 
* @param sql Mapper中的Sql語(yǔ)句 
* @param page 分頁(yè)對(duì)象 
* @param dialect 方言類(lèi)型 
* @return 分頁(yè)SQL 
*/ 
public static String generatePageSql(String sql, Page<Object> page, Dialect dialect) { 
if (dialect.supportsLimit()) { 
return dialect.getLimitString(sql, page.getFirstResult(), page.getMaxResults()); 
} else { 
return sql; 
} 
} 
/** 
* 去除qlString的select子句。 
* @param hql 
* @return 
*/ 
@SuppressWarnings("unused") 
private static String removeSelect(String qlString){ 
int beginPos = qlString.toLowerCase().indexOf("from"); 
return qlString.substring(beginPos); 
} 
/** 
* 去除hql的orderBy子句。 
* @param hql 
* @return 
*/ 
private static String removeOrders(String qlString) { 
Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE); 
Matcher m = p.matcher(qlString); 
StringBuffer sb = new StringBuffer(); 
while (m.find()) { 
m.appendReplacement(sb, ""); 
} 
m.appendTail(sb); 
return sb.toString(); 
} 
}

Dialect.java 接口

package com.store.base.secondmodel.base.dialect; 
/** 
* 類(lèi)似hibernate的Dialect,但只精簡(jiǎn)出分頁(yè)部分 
* @author yiyong_wu 
* 
*/ 
public interface Dialect { 
/** 
* 數(shù)據(jù)庫(kù)本身是否支持分頁(yè)當(dāng)前的分頁(yè)查詢(xún)方式 
* 如果數(shù)據(jù)庫(kù)不支持的話,則不進(jìn)行數(shù)據(jù)庫(kù)分頁(yè) 
* 
* @return true:支持當(dāng)前的分頁(yè)查詢(xún)方式 
*/ 
public boolean supportsLimit(); 
/** 
* 將sql轉(zhuǎn)換為分頁(yè)SQL,分別調(diào)用分頁(yè)sql 
* 
* @param sql SQL語(yǔ)句 
* @param offset 開(kāi)始條數(shù) 
* @param limit 每頁(yè)顯示多少紀(jì)錄條數(shù) 
* @return 分頁(yè)查詢(xún)的sql 
*/ 
public String getLimitString(String sql, int offset, int limit); 
}

MySQLDialect.java

package com.store.base.secondmodel.base.dialect; 
/** 
* Mysql方言的實(shí)現(xiàn) 
* @author yiyong_wu 
* 
*/ 
public class MySQLDialect implements Dialect { 
@Override 
public boolean supportsLimit() { 
return true; 
} 
@Override 
public String getLimitString(String sql, int offset, int limit) { 
return getLimitString(sql, offset, Integer.toString(offset),Integer.toString(limit)); 
} 
/** 
* 將sql變成分頁(yè)sql語(yǔ)句,提供將offset及l(fā)imit使用占位符號(hào)(placeholder)替換. 
* <pre> 
* 如mysql 
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 將返回 
* select * from user limit :offset,:limit 
* </pre> 
* 
* @param sql 實(shí)際SQL語(yǔ)句 
* @param offset 分頁(yè)開(kāi)始紀(jì)錄條數(shù) 
* @param offsetPlaceholder 分頁(yè)開(kāi)始紀(jì)錄條數(shù)-占位符號(hào) 
* @param limitPlaceholder 分頁(yè)紀(jì)錄條數(shù)占位符號(hào) 
* @return 包含占位符的分頁(yè)sql 
*/ 
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) { 
StringBuilder stringBuilder = new StringBuilder(sql); 
stringBuilder.append(" limit "); 
if (offset > 0) { 
stringBuilder.append(offsetPlaceholder).append(",").append(limitPlaceholder); 
} else { 
stringBuilder.append(limitPlaceholder); 
} 
return stringBuilder.toString(); 
} 
}

差不多到這邊已經(jīng)把整塊分頁(yè)怎么實(shí)現(xiàn)的給分享完了,但是我們還有更重要的任務(wù),想要整個(gè)東西跑起來(lái),肯定還要有基礎(chǔ)工作要做,接下去我們分析整套Page對(duì)象以及它所依據(jù)的三層架構(gòu),還是用product作為實(shí)體進(jìn)行分析。一整套三層架構(gòu)講下來(lái),收獲肯定又滿(mǎn)滿(mǎn)的。我們依次從entity->dao->service的順序講下來(lái)。

首先,針對(duì)我們的實(shí)體得繼承兩個(gè)抽象實(shí)體類(lèi)BaseEntity 與 DataEntity

BaseEntity.java 主要放置Page成員變量,繼承它后就可以每個(gè)實(shí)體都擁有這個(gè)成員變量

package com.store.base.secondmodel.base; 
import java.io.Serializable; 
import java.util.Map; 
import javax.xml.bind.annotation.XmlTransient; 
import org.apache.commons.lang3.StringUtils; 
import org.apache.commons.lang3.builder.ReflectionToStringBuilder; 
import com.fasterxml.jackson.annotation.JsonIgnore; 
import com.google.common.collect.Maps; 
import com.store.base.model.StoreUser; 
/** 
* 最頂層的Entity 
* @author yiyong_wu 
* 
* @param <T> 
*/ 
public abstract class BaseEntity<T> implements Serializable { 
private static final long serialVersionUID = 1L; 
/** 
* 刪除標(biāo)記(0:正常;1:刪除;2:審核;) 
*/ 
public static final String DEL_FLAG_NORMAL = "0"; 
public static final String DEL_FLAG_DELETE = "1"; 
public static final String DEL_FLAG_AUDIT = "2"; 
/** 
* 實(shí)體編號(hào)(唯一標(biāo)識(shí)) 
*/ 
protected String id; 
/** 
* 當(dāng)前用戶(hù) 
*/ 
protected StoreUser currentUser; 
/** 
* 當(dāng)前實(shí)體分頁(yè)對(duì)象 
*/ 
protected Page<T> page; 
/** 
* 自定義SQL(SQL標(biāo)識(shí),SQL內(nèi)容) 
*/ 
private Map<String, String> sqlMap; 
public BaseEntity() { 
} 
public BaseEntity(String id) { 
this(); 
this.id = id; 
} 
public String getId() { 
return id; 
} 
public void setId(String id) { 
this.id = id; 
} 
/** 
* 這個(gè)主要針對(duì)shiro執(zhí)行插入更新的時(shí)候會(huì)調(diào)用,獲取當(dāng)前的用戶(hù) 
* @return 
*/ 
@JsonIgnore 
@XmlTransient 
public StoreUser getCurrentUser() { 
if(currentUser == null){ 
// currentUser = UserUtils.getUser(); 
} 
return currentUser; 
} 
public void setCurrentUser(StoreUser currentUser) { 
this.currentUser = currentUser; 
} 
@JsonIgnore 
@XmlTransient 
public Page<T> getPage() { 
if (page == null){ 
page = new Page<>(); 
} 
return page; 
} 
public Page<T> setPage(Page<T> page) { 
this.page = page; 
return page; 
} 
@JsonIgnore 
@XmlTransient 
public Map<String, String> getSqlMap() { 
if (sqlMap == null){ 
sqlMap = Maps.newHashMap(); 
} 
return sqlMap; 
} 
public void setSqlMap(Map<String, String> sqlMap) { 
this.sqlMap = sqlMap; 
} 
/** 
* 插入之前執(zhí)行方法,子類(lèi)實(shí)現(xiàn) 
*/ 
public abstract void preInsert(); 
/** 
* 更新之前執(zhí)行方法,子類(lèi)實(shí)現(xiàn) 
*/ 
public abstract void preUpdate(); 
/** 
* 是否是新記錄(默認(rèn):false),調(diào)用setIsNewRecord()設(shè)置新記錄,使用自定義ID。 
* 設(shè)置為true后強(qiáng)制執(zhí)行插入語(yǔ)句,ID不會(huì)自動(dòng)生成,需從手動(dòng)傳入。 
* @return 
*/ 
public boolean getIsNewRecord() { 
return StringUtils.isBlank(getId()); 
} 
/** 
* 全局變量對(duì)象 
*/ 
@JsonIgnore 
public Global getGlobal() { 
return Global.getInstance(); 
} 
/** 
* 獲取數(shù)據(jù)庫(kù)名稱(chēng) 
*/ 
@JsonIgnore 
public String getDbName(){ 
return Global.getConfig("jdbc.type"); 
} 
@Override 
public String toString() { 
return ReflectionToStringBuilder.toString(this); 
} 
}

DataEntity.java,主要存儲(chǔ)更新刪除時(shí)間,創(chuàng)建用戶(hù),更新用戶(hù),邏輯刪除標(biāo)志等

package com.store.base.secondmodel.base; 
import java.util.Date; 
import org.hibernate.validator.constraints.Length; 
import com.fasterxml.jackson.annotation.JsonFormat; 
import com.fasterxml.jackson.annotation.JsonIgnore; 
import com.store.base.model.StoreUser; 
/** 
* 數(shù)據(jù)Entity 
* @author yiyong_wu 
* 
* @param <T> 
*/ 
public abstract class DataEntity<T> extends BaseEntity<T> { 
private static final long serialVersionUID = 1L; 
protected StoreUser createBy; // 創(chuàng)建者 
protected Date createDate; // 創(chuàng)建日期 
protected StoreUser updateBy; // 更新者 
protected Date updateDate; // 更新日期 
protected String delFlag; // 刪除標(biāo)記(0:正常;1:刪除;2:審核) 
public DataEntity() { 
super(); 
this.delFlag = DEL_FLAG_NORMAL; 
} 
public DataEntity(String id) { 
super(id); 
} 
/** 
* 插入之前執(zhí)行方法,需要手動(dòng)調(diào)用 
*/ 
@Override 
public void preInsert() { 
// 不限制ID為UUID,調(diào)用setIsNewRecord()使用自定義ID 
// User user = UserUtils.getUser(); 
// if (StringUtils.isNotBlank(user.getId())) { 
// this.updateBy = user; 
// this.createBy = user; 
// } 
this.updateDate = new Date(); 
this.createDate = this.updateDate; 
} 
/** 
* 更新之前執(zhí)行方法,需要手動(dòng)調(diào)用 
*/ 
@Override 
public void preUpdate() { 
// User user = UserUtils.getUser(); 
// if (StringUtils.isNotBlank(user.getId())) { 
// this.updateBy = user; 
// } 
this.updateDate = new Date(); 
} 
// @JsonIgnore 
public StoreUser getCreateBy() { 
return createBy; 
} 
public void setCreateBy(StoreUser createBy) { 
this.createBy = createBy; 
} 
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 
public Date getCreateDate() { 
return createDate; 
} 
public void setCreateDate(Date createDate) { 
this.createDate = createDate; 
} 
// @JsonIgnore 
public StoreUser getUpdateBy() { 
return updateBy; 
} 
public void setUpdateBy(StoreUser updateBy) { 
this.updateBy = updateBy; 
} 
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 
public Date getUpdateDate() { 
return updateDate; 
} 
public void setUpdateDate(Date updateDate) { 
this.updateDate = updateDate; 
} 
@JsonIgnore 
@Length(min = 1, max = 1) 
public String getDelFlag() { 
return delFlag; 
} 
public void setDelFlag(String delFlag) { 
this.delFlag = delFlag; 
} 
}

Product.java 產(chǎn)品類(lèi)

package com.store.base.secondmodel.pratice.model; 
import com.store.base.secondmodel.base.DataEntity; 
/** 
*產(chǎn)品基礎(chǔ)類(lèi) 
*2016年10月11日 
*yiyong_wu 
*/ 
public class Product extends DataEntity<Product>{ 
private static final long serialVersionUID = 1L; 
private String productName; 
private float price; 
private String productNo; 
public String getProductName() { 
return productName; 
} 
public void setProductName(String productName) { 
this.productName = productName; 
} 
public float getPrice() { 
return price; 
} 
public void setPrice(float price) { 
this.price = price; 
} 
public String getProductNo() { 
return productNo; 
} 
public void setProductNo(String productNo) { 
this.productNo = productNo; 
} 
}

怎么樣,是不是看到很復(fù)雜的一個(gè)實(shí)體繼承連關(guān)系,不過(guò)這有什么,越復(fù)雜就會(huì)越完整。接下來(lái)我就看看dao層,同樣是三層,準(zhǔn)備好接受洗禮吧

BaseDao.java 預(yù)留接口

package com.store.base.secondmodel.base; 
/** 
* 最頂層的DAO接口 
* @author yiyong_wu 
* 
*/ 
public interface BaseDao { 
} 
CrudDao.java 針對(duì)增刪改查的一個(gè)dao接口層
[java] view plain copy print?在CODE上查看代碼片派生到我的代碼片
package com.store.base.secondmodel.base; 
import java.util.List; 
/** 
* 定義增刪改查的DAO接口 
* @author yiyong_wu 
* 
* @param <T> 
*/ 
public interface CrudDao<T> extends BaseDao { 
/** 
* 獲取單條數(shù)據(jù) 
* @param id 
* @return 
*/ 
public T get(String id); 
/** 
* 獲取單條數(shù)據(jù) 
* @param entity 
* @return 
*/ 
public T get(T entity); 
/** 
* 查詢(xún)數(shù)據(jù)列表,如果需要分頁(yè),請(qǐng)?jiān)O(shè)置分頁(yè)對(duì)象,如:entity.setPage(new Page<T>()); 
* @param entity 
* @return 
*/ 
public List<T> findList(T entity); 
/** 
* 查詢(xún)所有數(shù)據(jù)列表 
* @param entity 
* @return 
*/ 
public List<T> findAllList(T entity); 
/** 
* 查詢(xún)所有數(shù)據(jù)列表 
* @see public List<T> findAllList(T entity) 
* @return 
public List<T> findAllList(); 
*/ 
/** 
* 插入數(shù)據(jù) 
* @param entity 
* @return 
*/ 
public int insert(T entity); 
/** 
* 更新數(shù)據(jù) 
* @param entity 
* @return 
*/ 
public int update(T entity); 
/** 
* 刪除數(shù)據(jù)(一般為邏輯刪除,更新del_flag字段為1) 
* @param id 
* @see public int delete(T entity) 
* @return 
*/ 
public int delete(String id); 
/** 
* 刪除數(shù)據(jù)(一般為邏輯刪除,更新del_flag字段為1) 
* @param entity 
* @return 
*/ 
public int delete(T entity); 
}

ProductDao.java mybatis對(duì)應(yīng)的接口mapper,同時(shí)也是dao實(shí)現(xiàn),這邊需要自定一個(gè)注解@MyBatisRepository

package com.store.base.secondmodel.pratice.dao; 
import com.store.base.secondmodel.base.CrudDao; 
import com.store.base.secondmodel.base.MyBatisRepository; 
import com.store.base.secondmodel.pratice.model.Product; 
/** 
*TODO 
*2016年10月11日 
*yiyong_wu 
*/ 
@MyBatisRepository 
public interface ProductDao extends CrudDao<Product>{ 
}

自定義注解MyBatisRepository.java,跟自定義注解相關(guān),這里就不做過(guò)多的解讀,網(wǎng)上資料一堆

package com.store.base.secondmodel.base; 
import java.lang.annotation.Documented; 
import java.lang.annotation.Retention; 
import java.lang.annotation.Target; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.ElementType; 
import org.springframework.stereotype.Component; 
/** 
* 標(biāo)識(shí)MyBatis的DAO,方便{@link org.mybatis.spring.mapper.MapperScannerConfigurer}的掃描。 
* 
* 請(qǐng)注意要在spring的配置文件中配置掃描該注解類(lèi)的配置 
* 
*<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
*<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 
*<property name="basePackage" value="com.store.base.secondmodel" /> 
*<property name="annotationClass" value="com.store.base.secondmodel.base.MyBatisRepository" /> 
*</bean> 
* @author yiyong_wu 
* 
*/ 
@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE) 
@Documented 
@Component 
public @interface MyBatisRepository { 
String value() default ""; 
}

注意:跟ProductDao.java聯(lián)系比較大的是ProductMapper.xml文件,大家可以看到上面那個(gè)配置文件的namespace是指向這個(gè)dao的路徑的。

接下來(lái)我們就進(jìn)入最后的service分析了,一樣還是三層繼承

BaseService.java

package com.store.base.secondmodel.base; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.transaction.annotation.Transactional; 
/** 
* Service的最頂層父類(lèi) 
* @author yiyong_wu 
* 
*/ 
@Transactional(readOnly = true) 
public abstract class BaseService { 
//日志記錄用的 
protected Logger logger = LoggerFactory.getLogger(getClass()); 
}

CrudService.java 增刪改查相關(guān)的業(yè)務(wù)接口實(shí)現(xiàn)

package com.store.base.secondmodel.base; 
import java.util.List; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.transaction.annotation.Transactional; 
/** 
* 增刪改查Service基類(lèi) 
* @author yiyong_wu 
* 
* @param <D> 
* @param <T> 
*/ 
public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity<T>> 
extends BaseService { 
/** 
* 持久層對(duì)象 
*/ 
@Autowired 
protected D dao; 
/** 
* 獲取單條數(shù)據(jù) 
* @param id 
* @return 
*/ 
public T get(String id) { 
return dao.get(id); 
} 
/** 
* 獲取單條數(shù)據(jù) 
* @param entity 
* @return 
*/ 
public T get(T entity) { 
return dao.get(entity); 
} 
/** 
* 查詢(xún)列表數(shù)據(jù) 
* @param entity 
* @return 
*/ 
public List<T> findList(T entity) { 
return dao.findList(entity); 
} 
/** 
* 查詢(xún)分頁(yè)數(shù)據(jù) 
* @param page 分頁(yè)對(duì)象 
* @param entity 
* @return 
*/ 
public Page<T> findPage(Page<T> page, T entity) { 
entity.setPage(page); 
page.setList(dao.findList(entity)); 
return page; 
} 
/** 
* 保存數(shù)據(jù)(插入或更新) 
* @param entity 
*/ 
@Transactional(readOnly = false) 
public void save(T entity) { 
if (entity.getIsNewRecord()){ 
entity.preInsert(); 
dao.insert(entity); 
}else{ 
entity.preUpdate(); 
dao.update(entity); 
} 
} 
/** 
* 刪除數(shù)據(jù) 
* @param entity 
*/ 
@Transactional(readOnly = false) 
public void delete(T entity) { 
dao.delete(entity); 
} 
}

ProductService.java,去繼承CrudService接口,注意起注入dao和實(shí)體類(lèi)型的一種模式

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>{ 
}

我想看到這里的同志已經(jīng)很不耐煩了。但是如果你錯(cuò)過(guò)接下去的一段,基本上剛才看的就快等于白看了,革命的勝利就在后半段,因?yàn)檎麄€(gè)分頁(yè)功能?chē)@的就是一個(gè)Page對(duì)象,重磅內(nèi)容終于要出來(lái)了,當(dāng)你把Page對(duì)象填充到剛才那個(gè)BaseEntity上的時(shí)候,你會(huì)發(fā)現(xiàn)一切就完整起來(lái)了,廢話不多說(shuō),Page對(duì)象如下

package com.store.base.secondmodel.base; 
import java.io.Serializable; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.regex.Pattern; 
import javax.servlet.http.HttpServletRequest; 
import 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; 
/** 
* 分頁(yè)類(lèi) 
* @author yiyong_wu 
* 
* @param <T> 
*/ 
public class Page<T> implements Serializable{ 
private static final long serialVersionUID = 1L; 
private int pageNo = 1; // 當(dāng)前頁(yè)碼 
private int pageSize = Integer.parseInt(Global.getConfig("page.pageSize")); // 頁(yè)面大小,設(shè)置為“-1”表示不進(jìn)行分頁(yè)(分頁(yè)無(wú)效) 
private long count;// 總記錄數(shù),設(shè)置為“-1”表示不查詢(xún)總數(shù) 
private int first;// 首頁(yè)索引 
private int last;// 尾頁(yè)索引 
private int prev;// 上一頁(yè)索引 
private int next;// 下一頁(yè)索引 
private boolean firstPage;//是否是第一頁(yè) 
private boolean lastPage;//是否是最后一頁(yè) 
private int length = 6;// 顯示頁(yè)面長(zhǎng)度 
private int slider = 1;// 前后顯示頁(yè)面長(zhǎng)度 
private List<T> list = new ArrayList<>(); 
private String orderBy = ""; // 標(biāo)準(zhǔn)查詢(xún)有效, 實(shí)例: updatedate desc, name asc 
private String funcName = "page"; // 設(shè)置點(diǎn)擊頁(yè)碼調(diào)用的js函數(shù)名稱(chēng),默認(rèn)為page,在一頁(yè)有多個(gè)分頁(yè)對(duì)象時(shí)使用。 
private String funcParam = ""; // 函數(shù)的附加參數(shù),第三個(gè)參數(shù)值。 
private String message = ""; // 設(shè)置提示消息,顯示在“共n條”之后 
public Page() { 
this.pageSize = -1; 
} 
/** 
* 構(gòu)造方法 
* @param request 傳遞 repage 參數(shù),來(lái)記住頁(yè)碼 
* @param response 用于設(shè)置 Cookie,記住頁(yè)碼 
*/ 
public Page(HttpServletRequest request, HttpServletResponse response){ 
this(request, response, -2); 
} 
/** 
* 構(gòu)造方法 
* @param request 傳遞 repage 參數(shù),來(lái)記住頁(yè)碼 
* @param response 用于設(shè)置 Cookie,記住頁(yè)碼 
* @param defaultPageSize 默認(rèn)分頁(yè)大小,如果傳遞 -1 則為不分頁(yè),返回所有數(shù)據(jù) 
*/ 
public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize){ 
// 設(shè)置頁(yè)碼參數(shù)(傳遞repage參數(shù),來(lái)記住頁(yè)碼) 
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)); 
} 
} 
// 設(shè)置頁(yè)面大小參數(shù)(傳遞repage參數(shù),來(lái)記住頁(yè)碼大?。?
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; 
} 
// 設(shè)置排序參數(shù) 
String orderBy = request.getParameter("orderBy"); 
if (StringUtils.isNotBlank(orderBy)){ 
this.setOrderBy(orderBy); 
} 
} 
/** 
* 構(gòu)造方法 
* @param pageNo 當(dāng)前頁(yè)碼 
* @param pageSize 分頁(yè)大小 
*/ 
public Page(int pageNo, int pageSize) { 
this(pageNo, pageSize, 0); 
} 
/** 
* 構(gòu)造方法 
* @param pageNo 當(dāng)前頁(yè)碼 
* @param pageSize 分頁(yè)大小 
* @param count 數(shù)據(jù)條數(shù) 
*/ 
public Page(int pageNo, int pageSize, long count) { 
this(pageNo, pageSize, count, new ArrayList<T>()); 
} 
/** 
* 構(gòu)造方法 
* @param pageNo 當(dāng)前頁(yè)碼 
* @param pageSize 分頁(yè)大小 
* @param count 數(shù)據(jù)條數(shù) 
* @param list 本頁(yè)數(shù)據(jù)對(duì)象列表 
*/ 
public Page(int pageNo, int pageSize, long count, List<T> list) { 
this.setCount(count); 
this.setPageNo(pageNo); 
this.pageSize = pageSize; 
this.list = list; 
} 
/** 
* 初始化參數(shù) 
*/ 
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) {// 如果當(dāng)前頁(yè)小于首頁(yè) 
this.pageNo = this.first; 
} 
if (this.pageNo > this.last) {// 如果當(dāng)前頁(yè)大于尾頁(yè) 
this.pageNo = this.last; 
} 
} 
/** 
* 默認(rèn)輸出當(dāng)前分頁(yè)標(biāo)簽 
* <div class="page">${page}</div> 
*/ 
@Override 
public String toString() { 
StringBuilder sb = new StringBuilder(); 
if (pageNo == first) {// 如果是首頁(yè) 
sb.append("<li class=\"disabled\"><a href=\"javascript:\">« 上一頁(yè)</a></li>\n"); 
} else { 
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+prev+","+pageSize+",'"+funcParam+"');\">« 上一頁(yè)</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:\">下一頁(yè) »</a></li>\n"); 
} else { 
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+next+","+pageSize+",'"+funcParam+"');\">" 
+ "下一頁(yè) »</a></li>\n"); 
} 
return sb.toString(); 
} 
/** 
* 獲取分頁(yè)HTML代碼 
* @return 
*/ 
public String getHtml(){ 
return toString(); 
} 
/** 
* 獲取設(shè)置總數(shù) 
* @return 
*/ 
public long getCount() { 
return count; 
} 
/** 
* 設(shè)置數(shù)據(jù)總數(shù) 
* @param count 
*/ 
public void setCount(long count) { 
this.count = count; 
if (pageSize >= count){ 
pageNo = 1; 
} 
} 
/** 
* 獲取當(dāng)前頁(yè)碼 
* @return 
*/ 
public int getPageNo() { 
return pageNo; 
} 
/** 
* 設(shè)置當(dāng)前頁(yè)碼 
* @param pageNo 
*/ 
public void setPageNo(int pageNo) { 
this.pageNo = pageNo; 
} 
/** 
* 獲取頁(yè)面大小 
* @return 
*/ 
public int getPageSize() { 
return pageSize; 
} 
/** 
* 設(shè)置頁(yè)面大?。ㄗ畲?00)// > 500 ? 500 : pageSize; 
* @param pageSize 
*/ 
public void setPageSize(int pageSize) { 
this.pageSize = pageSize <= 0 ? 10 : pageSize; 
} 
/** 
* 首頁(yè)索引 
* @return 
*/ 
@JsonIgnore 
public int getFirst() { 
return first; 
} 
/** 
* 尾頁(yè)索引 
* @return 
*/ 
@JsonIgnore 
public int getLast() { 
return last; 
} 
/** 
* 獲取頁(yè)面總數(shù) 
* @return getLast(); 
*/ 
@JsonIgnore 
public int getTotalPage() { 
return getLast(); 
} 
/** 
* 是否為第一頁(yè) 
* @return 
*/ 
@JsonIgnore 
public boolean isFirstPage() { 
return firstPage; 
} 
/** 
* 是否為最后一頁(yè) 
* @return 
*/ 
@JsonIgnore 
public boolean isLastPage() { 
return lastPage; 
} 
/** 
* 上一頁(yè)索引值 
* @return 
*/ 
@JsonIgnore 
public int getPrev() { 
if (isFirstPage()) { 
return pageNo; 
} else { 
return pageNo - 1; 
} 
} 
/** 
* 下一頁(yè)索引值 
* @return 
*/ 
@JsonIgnore 
public int getNext() { 
if (isLastPage()) { 
return pageNo; 
} else { 
return pageNo + 1; 
} 
} 
/** 
* 獲取本頁(yè)數(shù)據(jù)對(duì)象列表 
* @return List<T> 
*/ 
public List<T> getList() { 
return list; 
} 
/** 
* 設(shè)置本頁(yè)數(shù)據(jù)對(duì)象列表 
* @param list 
*/ 
public Page<T> setList(List<T> list) { 
this.list = list; 
initialize(); 
return this; 
} 
/** 
* 獲取查詢(xún)排序字符串 
* @return 
*/ 
@JsonIgnore 
public String getOrderBy() { 
// SQL過(guò)濾,防止注入 
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; 
} 
/** 
* 設(shè)置查詢(xún)排序,標(biāo)準(zhǔn)查詢(xún)有效, 實(shí)例: updatedate desc, name asc 
*/ 
public void setOrderBy(String orderBy) { 
this.orderBy = orderBy; 
} 
/** 
* 獲取點(diǎn)擊頁(yè)碼調(diào)用的js函數(shù)名稱(chēng) 
* function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;} 
* @return 
*/ 
@JsonIgnore 
public String getFuncName() { 
return funcName; 
} 
/** 
* 設(shè)置點(diǎn)擊頁(yè)碼調(diào)用的js函數(shù)名稱(chēng),默認(rèn)為page,在一頁(yè)有多個(gè)分頁(yè)對(duì)象時(shí)使用。 
* @param funcName 默認(rèn)為page 
*/ 
public void setFuncName(String funcName) { 
this.funcName = funcName; 
} 
/** 
* 獲取分頁(yè)函數(shù)的附加參數(shù) 
* @return 
*/ 
@JsonIgnore 
public String getFuncParam() { 
return funcParam; 
} 
/** 
* 設(shè)置分頁(yè)函數(shù)的附加參數(shù) 
* @return 
*/ 
public void setFuncParam(String funcParam) { 
this.funcParam = funcParam; 
} 
/** 
* 設(shè)置提示消息,顯示在“共n條”之后 
* @param message 
*/ 
public void setMessage(String message) { 
this.message = message; 
} 
/** 
* 分頁(yè)是否有效 
* @return this.pageSize==-1 
*/ 
@JsonIgnore 
public boolean isDisabled() { 
return this.pageSize==-1; 
} 
/** 
* 是否進(jìn)行總數(shù)統(tǒng)計(jì) 
* @return this.count==-1 
*/ 
@JsonIgnore 
public boolean isNotCount() { 
return this.count==-1; 
} 
/** 
* 獲取 Hibernate FirstResult 
*/ 
public int getFirstResult(){ 
int firstResult = (getPageNo() - 1) * getPageSize(); 
if (firstResult >= getCount()) { 
firstResult = 0; 
} 
return firstResult; 
} 
/** 
* 獲取 Hibernate MaxResults 
*/ 
public int getMaxResults(){ 
return getPageSize(); 
} 
}

看完這個(gè)Page對(duì)象應(yīng)該稍微有點(diǎn)感覺(jué)了吧,然后我在胡亂貼一些相關(guān)用到的工具類(lèi)吧,工具類(lèi)的話我只稍微提一下,具體大家可以弄到自己的代碼上好好解讀。

PropertiesLoader.java 用來(lái)獲取resource文件夾下的常量配置文件

package com.store.base.secondmodel.base.util; 
import 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文件載入工具類(lèi). 可載入多個(gè)properties文件, 
* 相同的屬性在最后載入的文件中的值將會(huì)覆蓋之前的值,但以System的Property優(yōu)先. 
* @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; 
} 
/** 
* 取出Property,但以System的Property優(yōu)先,取不到返回空字符串. 
*/ 
private String getValue(String key) { 
String systemProperty = System.getProperty(key); 
if (systemProperty != null) { 
return systemProperty; 
} 
if (properties.containsKey(key)) { 
return properties.getProperty(key); 
} 
return ""; 
} 
/** 
* 取出String類(lèi)型的Property,但以System的Property優(yōu)先,如果都為Null則拋出異常. 
*/ 
public String getProperty(String key) { 
String value = getValue(key); 
if (value == null) { 
throw new NoSuchElementException(); 
} 
return value; 
} 
/** 
* 取出String類(lèi)型的Property,但以System的Property優(yōu)先.如果都為Null則返回Default值. 
*/ 
public String getProperty(String key, String defaultValue) { 
String value = getValue(key); 
return value != null ? value : defaultValue; 
} 
/** 
* 取出Integer類(lèi)型的Property,但以System的Property優(yōu)先.如果都為Null或內(nèi)容錯(cuò)誤則拋出異常. 
*/ 
public Integer getInteger(String key) { 
String value = getValue(key); 
if (value == null) { 
throw new NoSuchElementException(); 
} 
return Integer.valueOf(value); 
} 
/** 
* 取出Integer類(lèi)型的Property,但以System的Property優(yōu)先.如果都為Null則返回Default值,如果內(nèi)容錯(cuò)誤則拋出異常 
*/ 
public Integer getInteger(String key, Integer defaultValue) { 
String value = getValue(key); 
return value != null ? Integer.valueOf(value) : defaultValue; 
} 
/** 
* 取出Double類(lèi)型的Property,但以System的Property優(yōu)先.如果都為Null或內(nèi)容錯(cuò)誤則拋出異常. 
*/ 
public Double getDouble(String key) { 
String value = getValue(key); 
if (value == null) { 
throw new NoSuchElementException(); 
} 
return Double.valueOf(value); 
} 
/** 
* 取出Double類(lèi)型的Property,但以System的Property優(yōu)先.如果都為Null則返回Default值,如果內(nèi)容錯(cuò)誤則拋出異常 
*/ 
public Double getDouble(String key, Integer defaultValue) { 
String value = getValue(key); 
return value != null ? Double.valueOf(value) : defaultValue.doubleValue(); 
} 
/** 
* 取出Boolean類(lèi)型的Property,但以System的Property優(yōu)先.如果都為Null拋出異常,如果內(nèi)容不是true/false則返回false. 
*/ 
public Boolean getBoolean(String key) { 
String value = getValue(key); 
if (value == null) { 
throw new NoSuchElementException(); 
} 
return Boolean.valueOf(value); 
} 
/** 
* 取出Boolean類(lèi)型的Property,但以System的Property優(yōu)先.如果都為Null則返回Default值,如果內(nèi)容不為true/false則返回false. 
*/ 
public Boolean getBoolean(String key, boolean defaultValue) { 
String value = getValue(key); 
return value != null ? Boolean.valueOf(value) : defaultValue; 
} 
/** 
* 載入多個(gè)文件, 文件路徑使用Spring Resource格式. 
*/ 
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 用來(lái)獲取全局的一些常量,可以是從配置文件中讀取的常量,也可以是定義成final static的常量,獲取配置文件的話是調(diào)用上面那個(gè)類(lèi)進(jìn)行獲取的。

package com.store.base.secondmodel.base; 
import java.io.File; 
import java.io.IOException; 
import 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; 
/** 
* 全局配置類(lèi) 
* @author yiyong_wu 
* 
*/ 
public class Global { 
private static final Logger logger = LoggerFactory.getLogger(Global.class); 
/** 
* 當(dāng)前對(duì)象實(shí)例 
*/ 
private static Global global = new Global(); 
/** 
* 保存全局屬性值 
*/ 
private static Map<String, String> map = Maps.newHashMap(); 
/** 
* 屬性文件加載對(duì)象 
*/ 
private static PropertiesLoader loader = new PropertiesLoader("application.properties"); 
/** 
* 顯示/隱藏 
public static final String SHOW = "1"; 
public static final String HIDE = "0"; 
/** 
* 是/否 
*/ 
public static final String YES = "1"; 
public static final String NO = "0"; 
/** 
* 狀態(tài) 上/下 app專(zhuān)用 
*/ 
public static final String UPSHVELF = "1"; 
public static final String DOWNSHVELF = "2"; 
public static final String SEPARATOR = "/"; 
/** 
* 對(duì)/錯(cuò) 
*/ 
public static final String TRUE = "true"; 
public static final String FALSE = "false"; 
/** 
* 上傳文件基礎(chǔ)虛擬路徑 
*/ 
public static final String USERFILES_BASE_URL = "/userfiles/"; 
/** 
* 針對(duì)富文本編輯器,結(jié)尾會(huì)產(chǎn)生的空div 
*/ 
public static final String ENDS = "<p><br></p>"; 
/** 
* 默認(rèn)空的私有構(gòu)造函數(shù) 
*/ 
public Global() { 
//do nothing in this method,just empty 
} 
/** 
* 獲取當(dāng)前對(duì)象實(shí)例 
*/ 
public static Global getInstance() { 
return global; 
} 
/** 
* 獲取配置 
*/ 
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; 
} 
/** 
* 獲取URL后綴 
*/ 
public static String getUrlSuffix() { 
return getConfig("urlSuffix"); 
} 
/** 
* 頁(yè)面獲取常量 
* @see ${fns:getConst('YES')} 
*/ 
public static Object getConst(String field) { 
try { 
return Global.class.getField(field).get(null); 
} catch (Exception e) { 
logger.error("獲取常量出錯(cuò)", e); 
} 
return null; 
} 
/** 
* 獲取工程路徑 
* @return 
*/ 
public static String getProjectPath(){ 
// 如果配置了工程路徑,則直接返回,否則自動(dòng)獲取。 
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("加載配置文件失敗", e); 
} 
return projectPath; 
} 
}

CookieUtil.java 從名稱(chēng)就知道是針對(duì)獲取和存儲(chǔ)cookie的一個(gè)工具類(lèi)

package com.store.base.secondmodel.base.util; 
import java.io.UnsupportedEncodingException; 
import java.net.URLDecoder; 
import java.net.URLEncoder; 
import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
/** 
* Cookie工具類(lèi) 
* @author yiyong_wu 
* 
*/ 
public class CookieUtils { 
private static final Logger logger = LoggerFactory.getLogger(CookieUtils.class); 
/** 
* 私有構(gòu)造函數(shù) 
*/ 
private CookieUtils() { 
} 
/** 
* 設(shè)置 Cookie(生成時(shí)間為1年) 
* @param name 名稱(chēng) 
* @param value 值 
*/ 
public static void setCookie(HttpServletResponse response, String name, String value) { 
setCookie(response, name, value, 60*60*24*365); 
} 
/** 
* 設(shè)置 Cookie 
* @param name 名稱(chēng) 
* @param value 值 
* @param maxAge 生存時(shí)間(單位秒) 
* @param uri 路徑 
*/ 
public static void setCookie(HttpServletResponse response, String name, String value, String path) { 
setCookie(response, name, value, path, 60*60*24*365); 
} 
/** 
* 設(shè)置 Cookie 
* @param name 名稱(chēng) 
* @param value 值 
* @param maxAge 生存時(shí)間(單位秒) 
* @param uri 路徑 
*/ 
public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) { 
setCookie(response, name, value, "/", maxAge); 
} 
/** 
* 設(shè)置 Cookie 
* @param name 名稱(chēng) 
* @param value 值 
* @param maxAge 生存時(shí)間(單位秒) 
* @param uri 路徑 
*/ 
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("不支持的編碼", e); 
} 
response.addCookie(cookie); 
} 
/** 
* 獲得指定Cookie的值 
* @param name 名稱(chēng) 
* @return 值 
*/ 
public static String getCookie(HttpServletRequest request, String name) { 
return getCookie(request, null, name, false); 
} 
/** 
* 獲得指定Cookie的值,并刪除。 
* @param name 名稱(chēng) 
* @return 值 
*/ 
public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) { 
return getCookie(request, response, name, true); 
} 
/** 
* 獲得指定Cookie的值 
* @param request 請(qǐng)求對(duì)象 
* @param response 響應(yīng)對(duì)象 
* @param name 名字 
* @param isRemove 是否移除 
* @return 值 
*/ 
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("不支持的編碼", e); 
} 
if (isRemove) { 
cookie.setMaxAge(0); 
response.addCookie(cookie); 
} 
} 
} 
return value; 
} 
}

SpringContextHolder.java 主要是用來(lái)在java代碼中獲取當(dāng)前的ApplicationContext,需要在spring配置文件中配置這個(gè)bean并且懶加載設(shè)置成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; 
/** 
* 取得存儲(chǔ)在靜態(tài)變量中的ApplicationContext. 
*/ 
public static ApplicationContext getApplicationContext() { 
assertContextInjected(); 
return applicationContext; 
} 
/** 
* 從靜態(tài)變量applicationContext中取得Bean, 自動(dòng)轉(zhuǎn)型為所賦值對(duì)象的類(lèi)型. 
*/ 
@SuppressWarnings("unchecked") 
public static <T> T getBean(String name) { 
assertContextInjected(); 
return (T) applicationContext.getBean(name); 
} 
/** 
* 從靜態(tài)變量applicationContext中取得Bean, 自動(dòng)轉(zhuǎn)型為所賦值對(duì)象的類(lèi)型. 
*/ 
public static <T> T getBean(Class<T> requiredType) { 
assertContextInjected(); 
return applicationContext.getBean(requiredType); 
} 
@Override 
public void destroy() throws Exception { 
SpringContextHolder.clearHolder(); 
} 
/** 
* 實(shí)現(xiàn)ApplicationContextAware接口, 注入Context到靜態(tài)變量中. 
*/ 
@Override 
public void setApplicationContext(ApplicationContext applicationContext) { 
logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext); 
SpringContextHolder.applicationContext = applicationContext; 
if (SpringContextHolder.applicationContext != null) { 
logger.info("SpringContextHolder中的ApplicationContext被覆蓋, 原有ApplicationContext為:" + SpringContextHolder.applicationContext); 
} 
} 
/** 
* 清除SpringContextHolder中的ApplicationContext為Null. 
*/ 
public static void clearHolder() { 
if (logger.isDebugEnabled()){ 
logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); 
} 
applicationContext = null; 
} 
/** 
* 檢查ApplicationContext不為空. 
*/ 
private static void assertContextInjected() { 
Validate.validState(applicationContext != null, "applicaitonContext屬性未注入, 請(qǐng)?jiān)赼pplicationContext.xml中定義SpringContextHolder."); 
} 
}

StringUtils.java字符串相關(guān)的一個(gè)工具類(lèi)

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; 
import 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; 
/** 
* 字符串幫助類(lèi) 
* @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); 
/** 
* 轉(zhuǎn)換為字節(jié)數(shù)組 
* @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]; 
} 
} 
/** 
* 轉(zhuǎn)換為字節(jié)數(shù)組 
* @param str 
* @return 
*/ 
public static String toString(byte[] bytes){ 
try { 
return new String(bytes, CHARSET_NAME); 
} catch (UnsupportedEncodingException e) { 
logger.error("", e); 
return EMPTY; 
} 
} 
/** 
* 是否包含字符串 
* @param str 驗(yàn)證字符串 
* @param strs 字符串組 
* @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; 
} 
/** 
* 替換掉HTML標(biāo)簽方法 
*/ 
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(""); 
} 
/** 
* 替換為手機(jī)識(shí)別的HTML,去掉樣式及屬性,保留回車(chē)。 
* @param html 
* @return 
*/ 
public static String replaceMobileHtml(String html){ 
if (html == null){ 
return ""; 
} 
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>"); 
} 
/** 
* 替換為手機(jī)識(shí)別的HTML,去掉樣式及屬性,保留回車(chē)。 
* @param txt 
* @return 
*/ 
public static String toHtml(String txt){ 
if (txt == null){ 
return ""; 
} 
return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", " "); 
} 
/** 
* 縮略字符串(不區(qū)分中英文字符) 
* @param str 目標(biāo)字符串 
* @param length 截取長(zhǎng)度 
* @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("..."); 
break; 
} 
} 
return sb.toString(); 
} catch (UnsupportedEncodingException e) { 
logger.error("", e); 
} 
return ""; 
} 
/** 
* 轉(zhuǎn)換為Double類(lèi)型 
*/ 
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; 
} 
} 
/** 
* 轉(zhuǎn)換為Float類(lèi)型 
*/ 
public static Float toFloat(Object val){ 
return toDouble(val).floatValue(); 
} 
/** 
* 轉(zhuǎn)換為L(zhǎng)ong類(lèi)型 
*/ 
public static Long toLong(Object val){ 
return toDouble(val).longValue(); 
} 
/** 
* 轉(zhuǎn)換為Integer類(lèi)型 
*/ 
public static Integer toInteger(Object val){ 
return toLong(val).intValue(); 
} 
/** 
* 獲得i18n字符串 
*/ 
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); 
} 
/** 
* 獲得用戶(hù)遠(yuǎn)程地址 
*/ 
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(); 
} 
/** 
* 駝峰命名法工具 
* @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); 
} 
} 
return sb.toString(); 
} 
/** 
* 駝峰命名法工具 
* @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); 
} 
/** 
* 駝峰命名法工具 
* @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(); 
} 
/** 
* 轉(zhuǎn)換為JS獲取對(duì)象值,生成三目運(yùn)算返回結(jié)果 
* @param objectString 對(duì)象串 
* 例如:row.user.id 
* 返回:!row?'':!row.user?'':!row.user.id?'':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(); 
} 
}

有了上面這些基礎(chǔ)的東西,只需要在寫(xiě)一個(gè)控制層接口,就可以看到每次返回一個(gè)page對(duì)象,然后里面封裝好了查詢(xún)對(duì)象的列表,并且是按分頁(yè)得出列表。

package com.store.controller; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.springframework.beans.factory.annotation.Autowired; 
import 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 
*2016年10月11日 
*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; 
} 
}

最后在看一下頁(yè)面怎么使用這個(gè)page對(duì)象,這樣我們就完整地介紹了這個(gè)一個(gè)分頁(yè)功能,代碼很多,但很完整。

<%@ 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(); 
return false; 
} 
</script> 
</head> 
<body> 
<form:form id="searchForm" modelAttribute="XXXX" action="${ctx}/XXX" method="post" class="breadcrumb form-search "> 
<input id="pageNo" name="pageNo" type="hidden" value="${page.pageNo}" /> 
<input id="pageSize" name="pageSize" type="hidden" value="${page.pageSize}" /> 
<ul class="ul-form"> 
<li> 
<label>是否上架:</label> 
<form:select id="status" path="status" class="input-medium"> 
<form:option value="" label=""/> 
<form:options items="${fns:getDictList('yes_no_app')}" itemLabel="label" itemValue="value" htmlEscape="false"/> 
</form:select> 
</li> 
<li class="btns"><input id="btnSubmit" class="btn btn-primary" type="submit" value="查詢(xún)"/> 
<li class="clearfix"></li> 
</ul> 
</form:form> 
<sys:message content="${message}" /> 
<sys:message content="${message}" /> 
<table id="contentTable" 
class="table table-striped table-bordered table-condensed"> 
<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> 
</tr> 
</thead> 
<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', '無(wú)')}</td> 
<td>${XXXX.}</td> 
<td><c:if test="${XXXX.status==1 }">上架</c:if> 
<c:if test="${XXXX.status==2 }">下架</c:if> 
</td> 
</tr> 
</c:forEach> 
</tbody> 
</table> 
<div class="pagination">${page} <li style="padding-top: 6px;padding-left: 12px;float: left;">共${page.count}條</li></div> 
</body> 
</html>

到這里就基本上把整個(gè)分頁(yè)功能描述得比較清楚了,希望可以幫助到你們快速解決分頁(yè)這個(gè)問(wèn)題,當(dāng)然要在前端顯示分頁(yè)漂亮的話要針對(duì)li做一些css樣式啥的,最后祝福你可以快速掌握這個(gè)分頁(yè)功能!

以上所述是小編給大家介紹的Mybatis常用分頁(yè)插件實(shí)現(xiàn)快速分頁(yè)處理技巧,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 詳解spring cloud config整合gitlab搭建分布式的配置中心

    詳解spring cloud config整合gitlab搭建分布式的配置中心

    這篇文章主要介紹了詳解spring cloud config整合gitlab搭建分布式的配置中心,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-01-01
  • elasticsearch源碼分析index?action實(shí)現(xiàn)方式

    elasticsearch源碼分析index?action實(shí)現(xiàn)方式

    這篇文章主要為大家介紹了elasticsearch源碼分析index?action實(shí)現(xiàn)方式,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-04-04
  • 詳解Kotlin中如何實(shí)現(xiàn)類(lèi)似Java或C#中的靜態(tài)方法

    詳解Kotlin中如何實(shí)現(xiàn)類(lèi)似Java或C#中的靜態(tài)方法

    Kotlin中如何實(shí)現(xiàn)類(lèi)似Java或C#中的靜態(tài)方法,本文總結(jié)了幾種方法,分別是:包級(jí)函數(shù)、伴生對(duì)象、擴(kuò)展函數(shù)和對(duì)象聲明。這需要大家根據(jù)不同的情況進(jìn)行選擇。
    2017-05-05
  • Spring需要三個(gè)級(jí)別緩存解決循環(huán)依賴(lài)原理解析

    Spring需要三個(gè)級(jí)別緩存解決循環(huán)依賴(lài)原理解析

    這篇文章主要為大家介紹了Spring需要三個(gè)級(jí)別緩存解決循環(huán)依賴(lài)原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-02-02
  • java獲取登錄者IP和登錄時(shí)間的兩種實(shí)現(xiàn)代碼詳解

    java獲取登錄者IP和登錄時(shí)間的兩種實(shí)現(xiàn)代碼詳解

    這篇文章主要介紹了java獲取登錄者IP和登錄時(shí)間的實(shí)現(xiàn)代碼,本文通過(guò)兩種結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-07-07
  • java基于servlet使用組件smartUpload實(shí)現(xiàn)文件上傳

    java基于servlet使用組件smartUpload實(shí)現(xiàn)文件上傳

    這篇文章主要介紹了java基于servlet使用組件smartUpload實(shí)現(xiàn)文件上傳,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • CentOS?7.9服務(wù)器Java部署環(huán)境配置的過(guò)程詳解

    CentOS?7.9服務(wù)器Java部署環(huán)境配置的過(guò)程詳解

    這篇文章主要介紹了CentOS?7.9服務(wù)器Java部署環(huán)境配置,主要包括ftp服務(wù)器搭建過(guò)程、jdk安裝方法以及mysql安裝過(guò)程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • Java Lambda表達(dá)式實(shí)例解析原理

    Java Lambda表達(dá)式實(shí)例解析原理

    日常開(kāi)發(fā)中,我們很多時(shí)候需要用到Java?8的Lambda表達(dá)式,它允許把函數(shù)作為一個(gè)方法的參數(shù),讓我們的代碼更優(yōu)雅、更簡(jiǎn)潔。所以整理了一波工作中常用的Lambda表達(dá)式??赐暌欢〞?huì)有幫助的
    2023-03-03
  • Java性能工具JMeter實(shí)現(xiàn)上傳與下載腳本編寫(xiě)

    Java性能工具JMeter實(shí)現(xiàn)上傳與下載腳本編寫(xiě)

    性能測(cè)試工作中,文件上傳也是經(jīng)常見(jiàn)的性能壓測(cè)場(chǎng)景之一,那么 JMeter 文件上傳下載腳本怎么做,本文詳細(xì)的來(lái)介紹一下,感興趣的可以了解一下
    2021-07-07
  • Java實(shí)現(xiàn)NIO聊天室的示例代碼(群聊+私聊)

    Java實(shí)現(xiàn)NIO聊天室的示例代碼(群聊+私聊)

    這篇文章主要介紹了Java實(shí)現(xiàn)NIO聊天室的示例代碼(群聊+私聊),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-05-05

最新評(píng)論