栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis常用分页插件实现快速分页处理技巧

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis常用分页插件实现快速分页处理技巧

在未分享整个查询分页的执行代码之前,先了解一下执行流程。

1.总体上是利用mybatis的插件拦截器,在sql执行之前拦截,为查询语句加上limit X X

2.用一个Page对象,贯穿整个执行流程,这个Page对象需要用Java编写前端分页组件

3.用一套比较完整的三层entity,dao,service支持这个分页架构

4.这个分页用到的一些辅助类

注:分享的内容较多,这边的话我就不把需要的jar一一列举,大家使用这个分页功能的时候缺少什么就去晚上找什么jar包即可,尽可能用maven包导入因为maven能减少版本冲突等比较好的优势。

我只能说尽可能让大家快速使用这个比较好用的分页功能,如果讲得不明白,欢迎加我QQ一起探讨1063150576,。莫喷哈!还有就是文章篇幅可能会比较大,不过花点时间,把它看完并实践一下一定会收获良多。

第一步:既然主题是围绕怎么进行分页的,我们就从mybatis入手,首先,我们把mybatis相关的两个比较重要的配置文件拿出来做简要的理解,一个是mybatis-config.xml,另外一个是实体所对应的mapper配置文件,我会在配置文件上写好注释,大家一看就会明白。

mybatis-config.xml

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

一个ProductMapper.xml作为测试对象,这个mapper文件就简单配置一个需要用到的查询语句

 
 
 
 
id, product_name as productName, product_no as productNo, price as price 
 
 
select  from t_store_product 
 

第二步:接下去主要针对这个分页拦截器进行深入分析学习,主要有以下几个类和其对应接口

(1)baseInterceptor 拦截器基础类

(2)PaginationInterceptor 我们要使用的分页插件类,继承上面基础类

(3)SQLHelper 主要是用来提前执行count语句,还有就是获取整个完整的分页语句

(4)Dialect,MysqlDialect,主要用来数据库是否支持limit语句,然后封装完整limit语句

以下是这几个类的分享展示

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; 
 
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; 
 
@SuppressWarnings("unchecked") 
protected static Page convertParameter(Object parameterObject, Page page) { 
try{ 
if (parameterObject instanceof Page) { 
return (Page) parameterObject; 
} else { 
return (Page)Reflections.getFieldValue(parameterObject, PAGE); 
} 
}catch (Exception e) { 
return null; 
} 
} 
 
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; 
 
@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(); 
// 获取分页参数对象 
Page page = null; 
if (parameterObject != null) { 
page = convertParameter(parameterObject, page); 
} 
// 如果设置了分页对象,则进行分页 
if (page != null && page.getPageSize() != -1) { 
if (StringUtils.isBlank(boundSql.getSql())) { 
return null; 
} 
String originalSql = boundSql.getSql().trim(); 
// 得到总记录数 
page.setCount(SQLHelper.getCount(originalSql, null,mappedStatement, parameterObject, boundSql, log)); 
// 分页查询 本地化对象 修改数据库注意修改实现 
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 分页foreach 参数失效 start 
if (Reflections.getFieldValue(boundSql, "metaParameters") != null) { 
metaObject mo = (metaObject) Reflections.getFieldValue( 
boundSql, "metaParameters"); 
Reflections.setFieldValue(newBoundSql, "metaParameters", mo); 
} 
// 解决MyBatis 分页foreach 参数失效 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; 
 
public class SQLHelper { 
 
private SQLHelper() { 
} 
 
@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 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()); 
} 
} 
} 
} 
 
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 分页foreach 参数失效 start 
if (Reflections.getFieldValue(boundSql, "metaParameters") != null) { 
metaObject mo = (metaObject) Reflections.getFieldValue(boundSql, "metaParameters"); 
Reflections.setFieldValue(countBS, "metaParameters", mo); 
} 
//解决MyBatis 分页foreach 参数失效 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(); 
} 
} 
} 
 
public static String generatePageSql(String sql, Page page, Dialect dialect) { 
if (dialect.supportsLimit()) { 
return dialect.getLimitString(sql, page.getFirstResult(), page.getMaxResults()); 
} else { 
return sql; 
} 
} 
 
@SuppressWarnings("unused") 
private static String removeSelect(String qlString){ 
int beginPos = qlString.toLowerCase().indexOf("from"); 
return qlString.substring(beginPos); 
} 
 
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; 
 
public interface Dialect { 
 
public boolean supportsLimit(); 
 
public String getLimitString(String sql, int offset, int limit); 
}

MySQLDialect.java

package com.store.base.secondmodel.base.dialect; 
 
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)); 
} 
 
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(); 
} 
}

差不多到这边已经把整块分页怎么实现的给分享完了,但是我们还有更重要的任务,想要整个东西跑起来,肯定还要有基础工作要做,接下去我们分析整套Page对象以及它所依据的三层架构,还是用product作为实体进行分析。一整套三层架构讲下来,收获肯定又满满的。我们依次从entity->dao->service的顺序讲下来。

首先,针对我们的实体得继承两个抽象实体类baseEntity 与 DataEntity

baseEntity.java 主要放置Page成员变量,继承它后就可以每个实体都拥有这个成员变量

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; 
 
public abstract class baseEntity implements Serializable { 
private static final long serialVersionUID = 1L; 
 
public static final String DEL_FLAG_NORMAL = "0"; 
public static final String DEL_FLAG_DELETE = "1"; 
public static final String DEL_FLAG_AUDIT = "2"; 
 
protected String id; 
 
protected StoreUser currentUser; 
 
protected Page page; 
 
private Map sqlMap; 
public baseEntity() { 
} 
public baseEntity(String id) { 
this(); 
this.id = id; 
} 
public String getId() { 
return id; 
} 
public void setId(String id) { 
this.id = id; 
} 
 
@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 getPage() { 
if (page == null){ 
page = new Page<>(); 
} 
return page; 
} 
public Page setPage(Page page) { 
this.page = page; 
return page; 
} 
@JsonIgnore 
@XmlTransient 
public Map getSqlMap() { 
if (sqlMap == null){ 
sqlMap = Maps.newHashMap(); 
} 
return sqlMap; 
} 
public void setSqlMap(Map sqlMap) { 
this.sqlMap = sqlMap; 
} 
 
public abstract void preInsert(); 
 
public abstract void preUpdate(); 
 
public boolean getIsNewRecord() { 
return StringUtils.isBlank(getId()); 
} 
 
@JsonIgnore 
public Global getGlobal() { 
return Global.getInstance(); 
} 
 
@JsonIgnore 
public String getDbName(){ 
return Global.getConfig("jdbc.type"); 
} 
@Override 
public String toString() { 
return ReflectionToStringBuilder.toString(this); 
} 
}

DataEntity.java,主要存储更新删除时间,创建用户,更新用户,逻辑删除标志等

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; 
 
public abstract class DataEntity extends baseEntity { 
private static final long serialVersionUID = 1L; 
protected StoreUser createBy; // 创建者 
protected Date createDate; // 创建日期 
protected StoreUser updateBy; // 更新者 
protected Date updateDate; // 更新日期 
protected String delFlag; // 删除标记(0:正常;1:删除;2:审核) 
public DataEntity() { 
super(); 
this.delFlag = DEL_FLAG_NORMAL; 
} 
public DataEntity(String id) { 
super(id); 
} 
 
@Override 
public void preInsert() { 
// 不限制ID为UUID,调用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; 
} 
 
@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 产品类

package com.store.base.secondmodel.pratice.model; 
import com.store.base.secondmodel.base.DataEntity; 
 
public class Product extends DataEntity{ 
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; 
} 
}

怎么样,是不是看到很复杂的一个实体继承连关系,不过这有什么,越复杂就会越完整。接下来我就看看dao层,同样是三层,准备好接受洗礼吧

baseDao.java 预留接口

package com.store.base.secondmodel.base; 
 
public interface baseDao { 
} 
CrudDao.java 针对增删改查的一个dao接口层
[java] view plain copy print?在CODE上查看代码片派生到我的代码片
package com.store.base.secondmodel.base; 
import java.util.List; 
 
public interface CrudDao extends baseDao { 
 
public T get(String id); 
 
public T get(T entity); 
 
public List findList(T entity); 
 
public List findAllList(T entity); 
 
 
public int insert(T entity); 
 
public int update(T entity); 
 
public int delete(String id); 
 
public int delete(T entity); 
}

ProductDao.java mybatis对应的接口mapper,同时也是dao实现,这边需要自定一个注解@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; 
 
@MyBatisRepository 
public interface ProductDao extends CrudDao{ 
}

自定义注解MyBatisRepository.java,跟自定义注解相关,这里就不做过多的解读,网上资料一堆

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; 
 
@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE) 
@documented 
@Component 
public @interface MyBatisRepository { 
String value() default ""; 
}

注意:跟ProductDao.java联系比较大的是ProductMapper.xml文件,大家可以看到上面那个配置文件的namespace是指向这个dao的路径的。

接下来我们就进入最后的service分析了,一样还是三层继承

baseService.java

package com.store.base.secondmodel.base; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.transaction.annotation.Transactional; 
 
@Transactional(readonly = true) 
public abstract class baseService { 
//日志记录用的 
protected Logger logger = LoggerFactory.getLogger(getClass()); 
}

CrudService.java 增删改查相关的业务接口实现

package com.store.base.secondmodel.base; 
import java.util.List; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.transaction.annotation.Transactional; 
 
public abstract class CrudService, T extends DataEntity> 
extends baseService { 
 
@Autowired 
protected D dao; 
 
public T get(String id) { 
return dao.get(id); 
} 
 
public T get(T entity) { 
return dao.get(entity); 
} 
 
public List findList(T entity) { 
return dao.findList(entity); 
} 
 
public Page findPage(Page page, T entity) { 
entity.setPage(page); 
page.setList(dao.findList(entity)); 
return page; 
} 
 
@Transactional(readonly = false) 
public void save(T entity) { 
if (entity.getIsNewRecord()){ 
entity.preInsert(); 
dao.insert(entity); 
}else{ 
entity.preUpdate(); 
dao.update(entity); 
} 
} 
 
@Transactional(readonly = false) 
public void delete(T entity) { 
dao.delete(entity); 
} 
}

ProductService.java,去继承CrudService接口,注意起注入dao和实体类型的一种模式

package com.store.base.secondmodel.pratice.service; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 
import com.store.base.secondmodel.base.CrudService; 
import com.store.base.secondmodel.pratice.dao.ProductDao; 
import com.store.base.secondmodel.pratice.model.Product; 
 
@Service 
@Transactional(readonly = true) 
public class ProductService extends CrudService{ 
}

我想看到这里的同志已经很不耐烦了。但是如果你错过接下去的一段,基本上刚才看的就快等于白看了,革命的胜利就在后半段,因为整个分页功能围绕的就是一个Page对象,重磅内容终于要出来了,当你把Page对象填充到刚才那个baseEntity上的时候,你会发现一切就完整起来了,废话不多说,Page对象如下

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; 
 
public class Page implements Serializable{ 
private static final long serialVersionUID = 1L; 
private int pageNo = 1; // 当前页码 
private int pageSize = Integer.parseInt(Global.getConfig("page.pageSize")); // 页面大小,设置为“-1”表示不进行分页(分页无效) 
private long count;// 总记录数,设置为“-1”表示不查询总数 
private int first;// 首页索引 
private int last;// 尾页索引 
private int prev;// 上一页索引 
private int next;// 下一页索引 
private boolean firstPage;//是否是第一页 
private boolean lastPage;//是否是最后一页 
private int length = 6;// 显示页面长度 
private int slider = 1;// 前后显示页面长度 
private List list = new ArrayList<>(); 
private String orderBy = ""; // 标准查询有效, 实例: updatedate desc, name asc 
private String funcName = "page"; // 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。 
private String funcParam = ""; // 函数的附加参数,第三个参数值。 
private String message = ""; // 设置提示消息,显示在“共n条”之后 
public Page() { 
this.pageSize = -1; 
} 
 
public Page(HttpServletRequest request, HttpServletResponse response){ 
this(request, response, -2); 
} 
 
public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize){ 
// 设置页码参数(传递repage参数,来记住页码) 
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)); 
} 
} 
// 设置页面大小参数(传递repage参数,来记住页码大小) 
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; 
} 
// 设置排序参数 
String orderBy = request.getParameter("orderBy"); 
if (StringUtils.isNotBlank(orderBy)){ 
this.setOrderBy(orderBy); 
} 
} 
 
public Page(int pageNo, int pageSize) { 
this(pageNo, pageSize, 0); 
} 
 
public Page(int pageNo, int pageSize, long count) { 
this(pageNo, pageSize, count, new ArrayList()); 
} 
 
public Page(int pageNo, int pageSize, long count, List list) { 
this.setCount(count); 
this.setPageNo(pageNo); 
this.pageSize = pageSize; 
this.list = list; 
} 
 
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) {// 如果当前页小于首页 
this.pageNo = this.first; 
} 
if (this.pageNo > this.last) {// 如果当前页大于尾页 
this.pageNo = this.last; 
} 
} 
 
@Override 
public String toString() { 
StringBuilder sb = new StringBuilder(); 
if (pageNo == first) {// 如果是首页 
sb.append("
  • « 上一页
  • n"); } else { sb.append("
  • « 上一页
  • 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("
  • " + (i + 1 - first) + "
  • n"); } if (i < begin) { sb.append("
  • ...
  • n"); } } for (int i = begin; i <= end; i++) { if (i == pageNo) { sb.append("
  • " + (i + 1 - first) + "
  • n"); } else { sb.append("
  • " + (i + 1 - first) + "
  • n"); } } if (last - end > slider) { sb.append("
  • ...
  • n"); end = last - slider; } for (int i = end + 1; i <= last; i++) { sb.append("
  • " + (i + 1 - first) + "
  • n"); } if (pageNo == last) { sb.append("
  • 下一页 »
  • n"); } else { sb.append("
  • " + "下一页 »
  • n"); } return sb.toString(); } public String getHtml(){ return toString(); } public long getCount() { return count; } public void setCount(long count) { this.count = count; if (pageSize >= count){ pageNo = 1; } } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize <= 0 ? 10 : pageSize; } @JsonIgnore public int getFirst() { return first; } @JsonIgnore public int getLast() { return last; } @JsonIgnore public int getTotalPage() { return getLast(); } @JsonIgnore public boolean isFirstPage() { return firstPage; } @JsonIgnore public boolean isLastPage() { return lastPage; } @JsonIgnore public int getPrev() { if (isFirstPage()) { return pageNo; } else { return pageNo - 1; } } @JsonIgnore public int getNext() { if (isLastPage()) { return pageNo; } else { return pageNo + 1; } } public List getList() { return list; } public Page setList(List list) { this.list = list; initialize(); return this; } @JsonIgnore public String getOrderBy() { // SQL过滤,防止注入 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; } public void setOrderBy(String orderBy) { this.orderBy = orderBy; } @JsonIgnore public String getFuncName() { return funcName; } public void setFuncName(String funcName) { this.funcName = funcName; } @JsonIgnore public String getFuncParam() { return funcParam; } public void setFuncParam(String funcParam) { this.funcParam = funcParam; } public void setMessage(String message) { this.message = message; } @JsonIgnore public boolean isDisabled() { return this.pageSize==-1; } @JsonIgnore public boolean isNotCount() { return this.count==-1; } public int getFirstResult(){ int firstResult = (getPageNo() - 1) * getPageSize(); if (firstResult >= getCount()) { firstResult = 0; } return firstResult; } public int getMaxResults(){ return getPageSize(); } }

    看完这个Page对象应该稍微有点感觉了吧,然后我在胡乱贴一些相关用到的工具类吧,工具类的话我只稍微提一下,具体大家可以弄到自己的代码上好好解读。

    PropertiesLoader.java 用来获取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; 
     
    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; 
    } 
     
    private String getValue(String key) { 
    String systemProperty = System.getProperty(key); 
    if (systemProperty != null) { 
    return systemProperty; 
    } 
    if (properties.containsKey(key)) { 
    return properties.getProperty(key); 
    } 
    return ""; 
    } 
     
    public String getProperty(String key) { 
    String value = getValue(key); 
    if (value == null) { 
    throw new NoSuchElementException(); 
    } 
    return value; 
    } 
     
    public String getProperty(String key, String defaultValue) { 
    String value = getValue(key); 
    return value != null ? value : defaultValue; 
    } 
     
    public Integer getInteger(String key) { 
    String value = getValue(key); 
    if (value == null) { 
    throw new NoSuchElementException(); 
    } 
    return Integer.valueOf(value); 
    } 
     
    public Integer getInteger(String key, Integer defaultValue) { 
    String value = getValue(key); 
    return value != null ? Integer.valueOf(value) : defaultValue; 
    } 
     
    public Double getDouble(String key) { 
    String value = getValue(key); 
    if (value == null) { 
    throw new NoSuchElementException(); 
    } 
    return Double.valueOf(value); 
    } 
     
    public Double getDouble(String key, Integer defaultValue) { 
    String value = getValue(key); 
    return value != null ? Double.valueOf(value) : defaultValue.doublevalue(); 
    } 
     
    public Boolean getBoolean(String key) { 
    String value = getValue(key); 
    if (value == null) { 
    throw new NoSuchElementException(); 
    } 
    return Boolean.valueOf(value); 
    } 
     
    public Boolean getBoolean(String key, boolean defaultValue) { 
    String value = getValue(key); 
    return value != null ? Boolean.valueOf(value) : defaultValue; 
    } 
     
    private Properties loadProperties(String... resourcesPaths) { 
    Properties props = new Properties(); 
    for (String location : resourcesPaths) { 
    InputStream is = null; 
    try { 
    Resource resource = resourceLoader.getResource(location); 
    is = resource.getInputStream(); 
    props.load(is); 
    } catch (IOException ex) { 
    logger.error("Could not load properties from path:" + location , ex); 
    } finally { 
    IOUtils.closeQuietly(is); 
    } 
    } 
    return props; 
    } 
    }

    Global.java 用来获取全局的一些常量,可以是从配置文件中读取的常量,也可以是定义成final static的常量,获取配置文件的话是调用上面那个类进行获取的。

    package com.store.base.secondmodel.base; 
    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; 
     
    public class Global { 
    private static final Logger logger = LoggerFactory.getLogger(Global.class); 
     
    private static Global global = new Global(); 
     
    private static Map map = Maps.newHashMap(); 
     
    private static PropertiesLoader loader = new PropertiesLoader("application.properties"); 
     
    public static final String YES = "1"; 
    public static final String NO = "0"; 
     
    public static final String UPSHVELF = "1"; 
    public static final String DOWNSHVELF = "2"; 
    public static final String SEPARATOR = "/"; 
     
    public static final String TRUE = "true"; 
    public static final String FALSE = "false"; 
     
    public static final String USERFILES_base_URL = "/userfiles/"; 
     
    public static final String ENDS = "


    "; public Global() { //do nothing in this method,just empty } 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; } public static String getUrlSuffix() { return getConfig("urlSuffix"); } public static Object getConst(String field) { try { return Global.class.getField(field).get(null); } catch (Exception e) { logger.error("获取常量出错", e); } return null; } public static String getProjectPath(){ // 如果配置了工程路径,则直接返回,否则自动获取。 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 从名称就知道是针对获取和存储cookie的一个工具类

    package com.store.base.secondmodel.base.util; 
    import java.io.UnsupportedEncodingException; 
    import java.net.URLDecoder; 
    import java.net.URLEncoder; 
    import javax.servlet.http.cookie; 
    import javax.servlet.http.HttpServletRequest; 
    import javax.servlet.http.HttpServletResponse; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 
     
    public class cookieUtils { 
    private static final Logger logger = LoggerFactory.getLogger(cookieUtils.class); 
     
    private cookieUtils() { 
    } 
     
    public static void setcookie(HttpServletResponse response, String name, String value) { 
    setcookie(response, name, value, 60*60*24*365); 
    } 
     
    public static void setcookie(HttpServletResponse response, String name, String value, String path) { 
    setcookie(response, name, value, path, 60*60*24*365); 
    } 
     
    public static void setcookie(HttpServletResponse response, String name, String value, int maxAge) { 
    setcookie(response, name, value, "/", maxAge); 
    } 
     
    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); 
    } 
     
    public static String getcookie(HttpServletRequest request, String name) { 
    return getcookie(request, null, name, false); 
    } 
     
    public static String getcookie(HttpServletRequest request, HttpServletResponse response, String name) { 
    return getcookie(request, response, name, true); 
    } 
     
    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 主要是用来在java代码中获取当前的ApplicationContext,需要在spring配置文件中配置这个bean并且懒加载设置成false;

    package com.store.base.secondmodel.base.util; 
    import org.apache.commons.lang3.Validate; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 
    import org.springframework.beans.factory.DisposableBean; 
    import org.springframework.context.ApplicationContext; 
    import org.springframework.context.ApplicationContextAware; 
    import org.springframework.context.annotation.Lazy; 
    import org.springframework.stereotype.Service; 
    @Service 
    @Lazy(false) 
    public class SpringContextHolder implements ApplicationContextAware, 
    DisposableBean { 
    private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); 
    private static ApplicationContext applicationContext = null; 
     
    public static ApplicationContext getApplicationContext() { 
    assertContextInjected(); 
    return applicationContext; 
    } 
     
    @SuppressWarnings("unchecked") 
    public static  T getBean(String name) { 
    assertContextInjected(); 
    return (T) applicationContext.getBean(name); 
    } 
     
    public static  T getBean(Class requiredType) { 
    assertContextInjected(); 
    return applicationContext.getBean(requiredType); 
    } 
    @Override 
    public void destroy() throws Exception { 
    SpringContextHolder.clearHolder(); 
    } 
     
    @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); 
    } 
    } 
     
    public static void clearHolder() { 
    if (logger.isDebugEnabled()){ 
    logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); 
    } 
    applicationContext = null; 
    } 
     
    private static void assertContextInjected() { 
    Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder."); 
    } 
    }

    StringUtils.java字符串相关的一个工具类

    package com.store.base.secondmodel.base.util; 
    import java.io.UnsupportedEncodingException; 
    import java.util.Locale; 
    import java.util.regex.Matcher; 
    import java.util.regex.Pattern; 
    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; 
     
    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); 
     
    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]; 
    } 
    } 
     
    public static String toString(byte[] bytes){ 
    try { 
    return new String(bytes, CHARSET_NAME); 
    } catch (UnsupportedEncodingException e) { 
    logger.error("", e); 
    return EMPTY; 
    } 
    } 
     
    public static boolean inString(String str, String... strs){ 
    if (str != null){ 
    for (String s : strs){ 
    if (str.equals(trim(s))){ 
    return true; 
    } 
    } 
    } 
    return false; 
    } 
     
    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(""); 
    } 
     
    public static String replaceMobileHtml(String html){ 
    if (html == null){ 
    return ""; 
    } 
    return html.replaceAll("<([a-z]+?)\s+?.*?>", "<$1>"); 
    } 
     
    public static String toHtml(String txt){ 
    if (txt == null){ 
    return ""; 
    } 
    return replace(replace(Encodes.escapeHtml(txt), "n", "
    "), "t", " "); } 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 ""; } 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; } } public static Float toFloat(Object val){ return toDouble(val).floatValue(); } public static Long toLong(Object val){ return toDouble(val).longValue(); } public static Integer toInteger(Object val){ return toLong(val).intValue(); } 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); } 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(); } 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(); } 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); } 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(); } public static String jsGetVal(String objectString){ StringBuilder result = new StringBuilder(); StringBuilder val = new StringBuilder(); String[] vals = split(objectString, "."); for (int i=0; i

    有了上面这些基础的东西,只需要在写一个控制层接口,就可以看到每次返回一个page对象,然后里面封装好了查询对象的列表,并且是按分页得出列表。

    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; 
     
    @RestController 
    @RequestMapping("/product") 
    public class ProductController { 
    @Autowired 
    private ProductService productService; 
    @ResponseBody 
    @RequestMapping(value="/getPageProduct") 
    public Page getPageProduct(HttpServletRequest request,HttpServletResponse response){ 
    Page page = productService.findPage(new Page(request,response), new Product()); 
    return page; 
    } 
    }

    最后在看一下页面怎么使用这个page对象,这样我们就完整地介绍了这个一个分页功能,代码很多,但很完整。

    <%@ page contentType="text/html;charset=UTF-8"%> 
    <%@ include file="/WEB-INF/views/include/taglib.jsp"%> 
     
     
     
     
    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; 
    } 
     
     
     
     
     
     
    
    XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX
    ${XXXX.name} ${XXXX.} ${XXXX.} ${XXXX.} ${XXXX.} ${fns:getDictLabel(XXXX.isHot, 'yes_no_app', '无')} ${XXXX.} 上架 下架
    ${page}
  • 共${page.count}条
  • 到这里就基本上把整个分页功能描述得比较清楚了,希望可以帮助到你们快速解决分页这个问题,当然要在前端显示分页漂亮的话要针对li做一些css样式啥的,最后祝福你可以快速掌握这个分页功能!

    以上所述是小编给大家介绍的Mybatis常用分页插件实现快速分页处理技巧,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

    转载请注明:文章转载自 www.mshxw.com
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号