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("");
String s1="";
String s2="";
if(currentPage==1){
s1="disabled";//禁用上一页
}
if(currentPage==lastPage||lastPage==0){
s2="disabled";//禁用下一页
}
if(s1.equals("disabled")){
sb.append("- «
");
}else{
sb.append("- «
");
}
if(currentPage-1>=4){//前面至少4页
sb.append("- 1
");//第一页
sb.append("- ...
");//省略号
if(currentPage==lastPage){//如果是最后一页
sb.append("- "+(currentPage-3)+"
");//前三页
}
sb.append("- "+(currentPage-2)+"
");//前二页
sb.append("- "+(currentPage-1)+"
");//前一页
}else {
for(int i=1;i"+i+"");//前面不超过4页把前面的都显示出来
}
}
sb.append("- "+currentPage+"
");//加上当前页码
if(lastPage-currentPage>=4){//后面至少4页
sb.append("- "+(currentPage+1)+"
");//后一页
sb.append("- "+(currentPage+2)+"
");//后二页
if(currentPage==1){//如果是第一页
sb.append("- "+(currentPage+3)+"
");//第三页
}
sb.append("- ...
");//省略号
sb.append("- "+lastPage+"
");//最后页
}else{
for(int i=currentPage+1;i<=lastPage;i++){
sb.append("- "+i+"
");//后面不超过4页把后面的都显示出来
}
}
if(s2.equals("disabled")){
sb.append("- »
");
}else{
sb.append("- »
");
}
sb.append("
");
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
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
接下来在mybatis里面配置分页插件
对数据库的操作采用sqlSessionTemplate,下面是service层方法
public List getPrealertlistPage(Page page) throws Exception {
return (List) dao.findForList("PrealertMapper.getPrealertlistPage", page);
}
对应的mapper的sql为
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: " ",
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= ""+
""+item.PrealertDate+" "+
"/orderList/toOrderDetail?orderID="+item.orderid+"&op=view \">"+item.OrderNumber+" "+
""+item.RefOrderNumber+" "+
" "+
" ";
tr+="\">"+
""+
" ";
if(item.PrealertStatus=='Initial'){
tr+="\">"+
""+
""+
" \" onclick=\"return confirm('Are you sure to delete?');\">"+
""+
""+
" "+
" ";
}else{
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 getPrelertList(
@RequestParam(value = "page", defaultValue = "1", required = true) Integer currentPage,
HttpSession session) {
Map retutnData=new HashMap();
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 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的分页