mybatis分页插件。

page类

包含了页面的信息

import com.zipx.util.PageData;
import com.zipx.util.Tools;

public class Page {
    
    private int showCount; //每页显示记录数
    private int totalPage;      //总页数
    private int totalResult;    //总记录数
    private int currentPage;    //当前页
    private int currentResult;  //当前记录起始索引
    private String pageStr;//最终页面显示的底部翻页导航ul,采用bootstrap样式
    private PageData pd = new PageData();//保存查询条件
    

    
    public Page(){
            this.showCount = 10;//默认10条
    }
    
    public int getTotalPage() {
        if(totalResult!=0){
            if(totalResult%showCount==0)
                totalPage = totalResult/showCount;
            else
                totalPage = totalResult/showCount+1;
        }else{
            totalPage=1;
        }
        return totalPage;
    }
    
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
    
    public int getTotalResult() {
        return totalResult;
    }
    
    public void setTotalResult(int totalResult) {
        this.totalResult = totalResult;
    }
    
    public int getCurrentPage() {
        return currentPage;
    }
    
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    

    
    public void setPageStr(String pageStr) {
         this.pageStr=pageStr;
    }
    
    public int getShowCount() {
        return showCount;
    }
    
    public void setShowCount(int showCount) {
        this.showCount = showCount;
    }
    
    public int getCurrentResult() {
        currentResult = (getCurrentPage()-1)*getShowCount();
        if(currentResult<0)
            currentResult = 0;
        return currentResult;
    }
    
    public void setCurrentResult(int currentResult) {
        this.currentResult = currentResult;
    }
    
    public PageData getPd() {
        return pd;
    }

    public void setPd(PageData pd) {
        this.pd = pd;
    }
    public  String getPageStr(){
        return this.pageStr;
    }
    public static void PageStr(Page p){
        int lastPage =p.getTotalPage();
        int currentPage=p.getCurrentPage();
        if(lastPage==0){
            lastPage=1;
            currentPage=1;
        }
        StringBuilder sb=new StringBuilder("<ul class='pagination pagination-lg'>");
        String s1="";
        String s2="";
        if(currentPage==1){
            s1="disabled";//禁用上一页
        }
        if(currentPage==lastPage||lastPage==0){
            s2="disabled";//禁用下一页
        }
        if(s1.equals("disabled")){
            sb.append("<li class='"+s1+"'><a>«</a></li>");
        }else{
         sb.append("<li class='"+s1+"'><a onclick=\"toPage("+(currentPage-1)+")\" >«</a></li>");
        }
        if(currentPage-1>=4){//前面至少4页
            sb.append("<li><a onclick=\"toPage(1)\">1</a></li>");//第一页
            sb.append("<li class=\""+"disabled"+"\"><span>...</span></li>");//省略号
            if(currentPage==lastPage){//如果是最后一页
                sb.append("<li><a onclick=\"toPage("+(currentPage-3)+")\" >"+(currentPage-3)+"</a></li>");//前三页
            }
            sb.append("<li><a onclick=\"toPage("+(currentPage-2)+")\" >"+(currentPage-2)+"</a></li>");//前二页
            sb.append("<li><a onclick=\"toPage("+(currentPage-1)+")\" >"+(currentPage-1)+"</a></li>");//前一页
        }else { 
            for(int i=1;i<currentPage;i++){ 
                sb.append("<li><a onclick=\"toPage("+i+")\" >"+i+"</a></li>");//前面不超过4页把前面的都显示出来
            }
        }
        sb.append("<li class=\"active\"><a onclick=\"toPage("+currentPage+")\" >"+currentPage+"</a></li>");//加上当前页码
        if(lastPage-currentPage>=4){//后面至少4页
            sb.append("<li><a onclick=\"toPage("+(currentPage+1)+")\">"+(currentPage+1)+"</a></li>");//后一页
            sb.append("<li><a onclick=\"toPage("+(currentPage+2)+")\">"+(currentPage+2)+"</a></li>");//后二页
            if(currentPage==1){//如果是第一页
                sb.append("<li><a onclick=\"toPage("+(currentPage+3)+")\" >"+(currentPage+3)+"</a></li>");//第三页
            }
            sb.append("<li class=\""+"disabled"+"\"><span>...</span></li>");//省略号
            sb.append("<li><a onclick=\"toPage("+lastPage+")\" >"+lastPage+"</a></li>");//最后页
        }else{
            for(int i=currentPage+1;i<=lastPage;i++){
                sb.append("<li><a onclick=\"toPage("+i+")\" >"+i+"</a></li>");//后面不超过4页把后面的都显示出来
            }
        }
        if(s2.equals("disabled")){
            sb.append("<li class='"+s2+"'><a>»</a></li>");
        }else{
            sb.append("<li class=\""+s2+"\"><a onclick=\"toPage("+(currentPage+1)+")\" >»</a></li>");
        }
        sb.append("</ul>");
        p.setPageStr(sb.toString());
    }
    
}
反射工具类
import java.lang.reflect.Field;

/**
 * @author Administrator
 *  反射工具
 */
public class ReflectHelper {
    /**
     * 获取obj对象fieldName的Field
     * @param obj
     * @param fieldName
     * @return
     */
    public static Field getFieldByFieldName(Object obj, String fieldName) {
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
            }
        }
        return null;
    }

    /**
     * 获取obj对象fieldName的属性值
     * @param obj
     * @param fieldName
     * @return
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static Object getValueByFieldName(Object obj, String fieldName)
            throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {
        Field field = getFieldByFieldName(obj, fieldName);
        Object value = null;
        if(field!=null){
            if (field.isAccessible()) {
                value = field.get(obj);
            } else {
                field.setAccessible(true);
                value = field.get(obj);
                field.setAccessible(false);
            }
        }
        return value;
    }

    /**
     * 设置obj对象fieldName的属性值
     * @param obj
     * @param fieldName
     * @param value
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void setValueByFieldName(Object obj, String fieldName,
            Object value) throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {
        Field field = obj.getClass().getDeclaredField(fieldName);
        if (field.isAccessible()) {
            field.set(obj, value);
        } else {
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
        }
    }
}
通用工具类

一个普普通通的类

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {
    
    /**
     * 随机生成六位数验证码 
     * @return
     */
    public static int getRandomNum(){
         Random r = new Random();
         return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
    }
    
    /**
     * 检测字符串是否不为空(null,"","null")
     * @param s
     * @return 不为空则返回true,否则返回false
     */
    public static boolean notEmpty(String s){
        return s!=null && !"".equals(s) && !"null".equals(s);
    }
    
    /**
     * 检测字符串是否为空(null,"","null")
     * @param s
     * @return 为空则返回true,不否则返回false
     */
    public static boolean isEmpty(String s){
        return s==null || "".equals(s) || "null".equals(s);
    }
    
    /**
     * 字符串转换为字符串数组
     * @param str 字符串
     * @param splitRegex 分隔符
     * @return
     */
    public static String[] str2StrArray(String str,String splitRegex){
        if(isEmpty(str)){
            return null;
        }
        return str.split(splitRegex);
    }
    
    /**
     * 用默认的分隔符(,)将字符串转换为字符串数组
     * @param str   字符串
     * @return
     */
    public static String[] str2StrArray(String str){
        return str2StrArray(str,",\\s*");
    }
    
    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式,日期转字符串
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String date2Str(Date date){
        return date2Str(date,"yyyy-MM-dd HH:mm:ss");
    }
    
    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式,字符串转日期
     * @param date
     * @return
     */
    public static Date str2Date(String date){
        if(notEmpty(date)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return sdf.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        }else{
            return null;
        }
    }
    
    /**
     * 按照参数format的格式,日期转字符串
     * @param date
     * @param format
     * @return
     */
    public static String date2Str(Date date,String format){
        if(date!=null){
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        }else{
            return "";
        }
    }
    
    /**
     * 把时间根据时、分、秒转换为时间段
     * @param StrDate
     */
    public static String getTimes(String StrDate){
        String resultTimes = "";
        
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date now;
        
        try {
            now = new Date();
            java.util.Date date=df.parse(StrDate);
            long times = now.getTime()-date.getTime();
            long day  =  times/(24*60*60*1000);
            long hour = (times/(60*60*1000)-day*24);
            long min  = ((times/(60*1000))-day*24*60-hour*60);
            long sec  = (times/1000-day*24*60*60-hour*60*60-min*60);
            
            StringBuffer sb = new StringBuffer();
            //sb.append("发表于:");
            if(hour>0 ){
                sb.append(hour+"小时前");
            } else if(min>0){
                sb.append(min+"分钟前");
            } else{
                sb.append(sec+"秒前");
            }
                
            resultTimes = sb.toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        return resultTimes;
    }
    
    /**
     * 写txt里的单行内容
     * @param filePath  文件路径
     * @param content  写入的内容
     */
    public static void writeFile(String fileP,String content){
        String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";  //项目路径
        filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
        if(filePath.indexOf(":") != 1){
            filePath = File.separator + filePath;
        }
        try {
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");      
            BufferedWriter writer=new BufferedWriter(write);          
            writer.write(content);      
            writer.close(); 

            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
      * 验证邮箱
      * @param email
      * @return
      */
     public static boolean checkEmail(String email){
      boolean flag = false;
      try{
        String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        flag = matcher.matches();
       }catch(Exception e){
        flag = false;
       }
      return flag;
     }
    
     /**
      * 验证手机号码
      * @param mobiles
      * @return
      */
     public static boolean checkMobileNumber(String mobileNumber){
      boolean flag = false;
      try{
        Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
        Matcher matcher = regex.matcher(mobileNumber);
        flag = matcher.matches();
       }catch(Exception e){
        flag = false;
       }
      return flag;
     }
     
    /**
     * 检测KEY是否正确
     * @param paraname  传入参数
     * @param FKEY      接收的 KEY
     * @return 为空则返回true,不否则返回false
     */
    public static boolean checkKey(String paraname, String FKEY){
        paraname = (null == paraname)? "":paraname;
        return MD5.md5(paraname+DateUtil.getDays()+",fh,").equals(FKEY);
    }
     
    /**
     * 读取txt里的单行内容
     * @param filePath  文件路径
     */
    public static String readTxtFile(String fileP) {
        try {
            
            String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";  //项目路径
            filePath = filePath.replaceAll("file:/", "");
            filePath = filePath.replaceAll("%20", " ");
            filePath = filePath.trim() + fileP.trim();
            if(filePath.indexOf(":") != 1){
                filePath = File.separator + filePath;
            }
            String encoding = "utf-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {       // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file), encoding);   // 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    return lineTxt;
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件,查看此路径是否正确:"+filePath);
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
        }
        return "";
    }
    
    

}
分页插件类

分页最主要的类

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.xml.bind.PropertyException;

import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
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.plugin.Interceptor;
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.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.zipx.entity.Page;
import com.zipx.util.ReflectHelper;
import com.zipx.util.Tools;

@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
public class PagePlugin implements Interceptor {

    private static String dialect = ""; //数据库方言
    private static String pageSqlId = ""; //mapper.xml中需要拦截的ID(正则匹配)
    
    public Object intercept(Invocation ivk) throws Throwable {
        // TODO Auto-generated method stub
        if(ivk.getTarget() instanceof RoutingStatementHandler){
            RoutingStatementHandler statementHandler = (RoutingStatementHandler)ivk.getTarget();
            BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
            MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");
            
            if(mappedStatement.getId().matches(pageSqlId)){ //拦截需要分页的SQL
                BoundSql boundSql = delegate.getBoundSql();
                Object parameterObject = boundSql.getParameterObject();//分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
                if(parameterObject==null){
                    throw new NullPointerException("parameterObject尚未实例化!");
                }else{
                    Connection connection = (Connection) ivk.getArgs()[0];
                    String sql = boundSql.getSql();
                    //String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //记录统计
                    String countSql = "select count(0) from (" + sql+ ")  tmp_count"; //记录统计 == oracle 加 as 报错(SQL command not properly ended)
                    PreparedStatement countStmt = connection.prepareStatement(countSql);
                    BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(),countSql,boundSql.getParameterMappings(),parameterObject);
                    setParameters(countStmt,mappedStatement,countBS,parameterObject);
                    ResultSet rs = countStmt.executeQuery();
                    int count = 0;
                    if (rs.next()) {
                        count = rs.getInt(1);
                    }
                    rs.close();
                    countStmt.close();
                    //System.out.println(count);
                    Page page = null;
                    if(parameterObject instanceof Page){    //参数就是Page实体
                         page = (Page) parameterObject;
                         page.setEntityOrField(true);    
                        page.setTotalResult(count);
                    }else{  //参数为某个实体,该实体拥有Page属性
                        Field pageField = ReflectHelper.getFieldByFieldName(parameterObject,"page");
                        if(pageField!=null){
                            page = (Page) ReflectHelper.getValueByFieldName(parameterObject,"page");
                            if(page==null)
                                page = new Page();
                            page.setEntityOrField(false); 
                            page.setTotalResult(count);
                            ReflectHelper.setValueByFieldName(parameterObject,"page", page); //通过反射,对实体对象设置分页对象
                        }else{
                            throw new NoSuchFieldException(parameterObject.getClass().getName()+"不存在 page 属性!");
                        }
                    }
                    String pageSql = generatePageSql(sql,page);
                    ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); //将分页sql语句反射回BoundSql.
                }
            }
        }
        return ivk.proceed();
    }

    
    /**
     * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
     * @param ps
     * @param mappedStatement
     * @param boundSql
     * @param parameterObject
     * @throws SQLException
     */
    private 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);
                    }
                    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());
                }
            }
        }
    }
    
    /**
     * 根据数据库方言,生成特定的分页sql
     * @param sql
     * @param page
     * @return
     */
    private String generatePageSql(String sql,Page page){
        if(page!=null && Tools.notEmpty(dialect)){
            StringBuffer pageSql = new StringBuffer();
            if("mysql".equals(dialect)){
                pageSql.append(sql);
                pageSql.append(" limit "+page.getCurrentResult()+","+page.getShowCount());
            }else if("oracle".equals(dialect)){
                pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from (");
                pageSql.append(sql);
                //pageSql.append(") as tmp_tb where ROWNUM<=");
                pageSql.append(") tmp_tb where ROWNUM<=");
                pageSql.append(page.getCurrentResult()+page.getShowCount());
                pageSql.append(") where row_id>");
                pageSql.append(page.getCurrentResult());
            }
            return pageSql.toString();
        }else{
            return sql;
        }
    }
    
    public Object plugin(Object arg0) {
        // TODO Auto-generated method stub
        return Plugin.wrap(arg0, this);
    }

    public void setProperties(Properties p) {
        dialect = p.getProperty("dialect");
        if (Tools.isEmpty(dialect)) {
            try {
                throw new PropertyException("dialect property is not found!");
            } catch (PropertyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        pageSqlId = p.getProperty("pageSqlId");
        if (Tools.isEmpty(pageSqlId)) {
            try {
                throw new PropertyException("pageSqlId property is not found!");
            } catch (PropertyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
}
PageData类

可以放入request获得页面请求的数据,也可以当做数据载体来使用


import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

public class PageData extends HashMap implements Map{
    
    private static final long serialVersionUID = 1L;
    
    Map map = null;
    HttpServletRequest request;
    
    public PageData(HttpServletRequest request){
        this.request = request;
        Map properties = request.getParameterMap();
        Map returnMap = new HashMap(); 
        Iterator entries = properties.entrySet().iterator(); 
        Map.Entry entry; 
        String name = "";  
        String value = "";  
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next(); 
            name = (String) entry.getKey(); 
            Object valueObj = entry.getValue(); 
            if(null == valueObj){ 
                value = ""; 
            }else if(valueObj instanceof String[]){ 
                String[] values = (String[])valueObj;
                for(int i=0;i<values.length;i++){ 
                     value = values[i] + ",";
                }
                value = value.substring(0, value.length()-1); 
            }else{
                value = valueObj.toString(); 
            }
            returnMap.put(name, value); 
        }
        map = returnMap;
    }
    
    public PageData() {
        map = new HashMap();
    }
    
    @Override
    public Object get(Object key) {
        Object obj = null;
        if(map.get(key) instanceof Object[]) {
            Object[] arr = (Object[])map.get(key);
            obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
        } else {
            obj = map.get(key);
        }
        return obj;
    }
    public Date getStringDate(String date){
        if(DateUtil.isValidDate(date)){
            return DateUtil.fomatDate(date);
        }else{
            return null;
        }
        
        
    }
    public Integer getInteger(Object key){
        return (Integer)key;
    }
    public String getString(Object key) {
        return (String)get(key);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public Object put(Object key, Object value) {
        return map.put(key, value);
    }
    
    @Override
    public Object remove(Object key) {
        return map.remove(key);
    }

    public void clear() {
        map.clear();
    }

    public boolean containsKey(Object key) {
        // TODO Auto-generated method stub
        return map.containsKey(key);
    }

    public boolean containsValue(Object value) {
        // TODO Auto-generated method stub
        return map.containsValue(value);
    }

    public Set entrySet() {
        // TODO Auto-generated method stub
        return map.entrySet();
    }

    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return map.isEmpty();
    }

    public Set keySet() {
        // TODO Auto-generated method stub
        return map.keySet();
    }

    @SuppressWarnings("unchecked")
    public void putAll(Map t) {
        // TODO Auto-generated method stub
        map.putAll(t);
    }

    public int size() {
        // TODO Auto-generated method stub
        return map.size();
    }

    public Collection values() {
        // TODO Auto-generated method stub
        return map.values();
    }
    
}

接下来在mybatis里面配置分页插件

    <typeAliases>
        <!-- 分页 -->
        <typeAlias type="com.zipx.entity.Page" alias="Page" />
    </typeAliases>

    <plugins>
        <plugin interceptor="com.zipx.plugin.PagePlugin">
            <!--  表示数据库为mysql-->
            <property name="dialect" value="mysql" />
            <!-- sql的id的匹配表达式,会拦截执行的sql语句-->
            <property name="pageSqlId" value=".*listPage.*" />
        </plugin>
    </plugins>

对数据库的操作采用sqlSessionTemplate,下面是service层方法

public List<PageData> getPrealertlistPage(Page page) throws Exception {
        return (List<PageData>) dao.findForList("PrealertMapper.getPrealertlistPage", page);
    }

对应的mapper的sql为

<select id="getPrealertlistPage" parameterType="Page" resultType="pd">
            SELECT p.PrealertID,
            DATE_FORMAT(PrealertDate,'%Y-%m-%d') as 'PrealertDate',
            p.OrderNumber,p.RefOrderNumber,p.PrealertStatus,o.orderid from prealertheader p LEFT JOIN orderheader o on p.OrderNumber=o.OrderNumber
            WHERE 1=1
            <if test="pd.SalesMarketID != null and pd.SalesMarketID != ''">
            and p.SaledMarketID=#{pd.SalesMarketID}
            </if>
            <if test="pd.WarehouseID != null and pd.WarehouseID != ''">
            and p.WarehouseID=#{pd.WarehouseID}
            </if>
            <if test="pd.StartDate != null and pd.StartDate != ''">
            and DATE_FORMAT(p.PrealertDate,'%Y-%m-%d') >= #{pd.StartDate}
            </if>
            <if test="pd.EndDate != null and pd.EndDate != ''">
            and DATE_FORMAT(p.PrealertDate,'%Y-%m-%d') <![CDATA[<=]]> #{pd.EndDate}
            </if>
            <if test="pd.RefOrderNumber != null and pd.RefOrderNumber != ''">
            and p.RefOrderNumber LIKE CONCAT('%',#{pd.RefOrderNumber},'%')
            </if>
            <if test="pd.PrealertStatus == null or pd.PrealertStatus == ''">
            and p.PrealertStatus != 'Deleted'
            </if>
            <if test="pd.PrealertStatus != null and pd.PrealertStatus != ''">
            and p.PrealertStatus = #{pd.PrealertStatus}
            </if>
            order by PrealertDate desc
        </select>

sql直接写查询sql语句即可,后面不用跟limit,因为配置了分页插件,会自动分页,下面看页面js

$(function(){
                var index=location.hash.indexOf("#!page=");
                var page = 1;
                if(index!=-1){
                    page=location.hash.substring(index+7);
                }
                toPage(page);
                $('#search').click(function(){
                    toPage(1);
                    location.hash="!page=1";
                });
            });
            function toPage(page){
                var startDate=$('#StartDate').val();
                var endDate=$('#EndDate').val();
                var orderNumber=$('#OrderNumber').val();
                var prealertStatus=$('#PrealertStatus').val();
                  $.ajax({
                       url: "<c:url value='/Order/getPrelertList'/>",
                       type: 'post',
                       data:{
                           page:page,
                           StartDate:startDate,
                           EndDate:endDate,
                           RefOrderNumber:orderNumber,
                           PrealertStatus:prealertStatus
                           },
                       dataType:'json',
                       async: false,
                        success: function (data) {
                            var $tbody =$('#t1 tbody');
                            $tbody.empty();
                            $.each(data.pageData,function(i,item){
                               //数据填充表格
                                var tr= "<tr>"+
                                "<td class=\"table-col-center\">"+item.PrealertDate+"</td>"+
                                "<td><a href=\"<%=path%>/orderList/toOrderDetail?orderID="+item.orderid+"&op=view \">"+item.OrderNumber+"</a></td>"+
                                "<td class=\"col-auto-hide\">"+item.RefOrderNumber+"</td>"+
                                "<td class=\"col-auto-hide-half\">"+item.PrealertStatus+"</td>"+
                                "<td class=\"table-col-center\"><span style=\"font-size: 16px;\"> ";
                                
                                tr+="<a href=\"<c:url value='/Order/PrelertDetail?PrealertID="+item.PrealertID+"&action=view'/>\">"+
                                    "<i class=\"fa fa-search\"></i>"+
                                    "</a>  ";
                                if(item.PrealertStatus=='Initial'){
                                    tr+="<a href=\"<c:url value='/Order/PrelertDetail?PrealertID="+item.PrealertID+"&action=edit'/>\">"+
                                    "<i class=\"fa fa-edit\"></i>"+
                                    "</a>"+
                                     "  <a href=\"<c:url value='/Prealert/deletePrealertById?PrealertID="+item.PrealertID+"'/>\" onclick=\"return confirm('Are you sure to delete?');\">"+
                                     "<i class=\"fa fa-remove\"></i>"+
                                     "</a>"+
                                    "</span></td>"+
                                "</tr>";
                                }else{
                                    tr+="</span></td>"+
                                    "</tr>";
                                }
                                $tbody.append(tr);
                            });
                            location.hash="!page="+data.pageInfo.currentPage;
            //pagination    为一个div,存放分页的ul
            $("#pagination").html(data.pageInfo.pageStr);
                        }
                  });
                
            }

下面为controller部分代码

    @RequestMapping("/Order/getPrelertList")
    @ResponseBody
    public Map<String,Object> getPrelertList(
            @RequestParam(value = "page", defaultValue = "1", required = true) Integer currentPage,
HttpSession session) {
        Map<String,Object> retutnData=new HashMap<String, Object>();
        PageData pd = this.getPageData();//basecontroller的方法
        SystemUser s = (SystemUser) session.getAttribute(Const.SESSION_USER);
        try {
            String id = systemUserService.getWareHouseIdByUserId(s.getsystemUserID());
            pd.put("WarehouseID", id);
            Page pageInfo = new Page();
            pageInfo.setCurrentPage(currentPage);
            pageInfo.setPd(pd);
            List<PageData> pds = prealertService.getPrealertlistPage(pageInfo);
            Page.PageStr(pageInfo);
            retutnData.put("pageData", pds);//设置数据
            retutnData.put("pageInfo",pageInfo);//设置分页信息
        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        }
        return retutnData;
    }

basecontroller部分代码

    
    /**
     * 得到request对象
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }
    /**
     * 得到PageData
     */
    public PageData getPageData(){
        return new PageData(this.getRequest());
    }

到此完成ajax的分页

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容