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();
}
}
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);
}
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();
}
}
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;
}
}
<%@ 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;
}