上一节很重要:ssm+maven搭建及扩展修改(六.封装公共数据操作-未分页)
思路:
- 分页肯定是有页数,每页数据条数(便于计算位置,后面看代码知道),查询条件,还有要显示
- 前端传递第一步的数据(除显示数据list,这是返回的)去后台,那么这里要封装下,规范请求参数。(PageParam <T>,自定义查询条件param,PersonParam)
- 页数,每页数据条数,这简单。关键是查询条件,封装一下,不要for去拿再添加麻烦。 (PageWhere<T>)
- 返回数据封装。(Page <T>)
- 前几步准备好,修改dao,service,conctoller。。。看具体实例。
注意了,很重要,很重要:-------附上前后端代码包---------
目录
第一步:前端请求规范化
1.封装PageParam <T>,创建文件
package org.test.bean.param;
public class PageParam <T>{
private Integer page = 1; //当前页
private Integer size = 5;//每页默认为5
private T param = null;
public PageParam() {
page = 1;
size = 5;
param = null;
}
/**
* @return the size
*/
public Integer getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(Integer size) {
this.size = size;
}
/**
* @return the page
*/
public Integer getPage() {
return page;
}
/**
* @return the param
*/
public T getParam() {
return param;
}
/**
* @param param the param to set
*/
public void setParam(T param) {
this.param = param;
}
/**
* @param page the page to set
*/
public void setPage(Integer page) {
this.page = page;
}
}
2.封装PersonParam,创建文件
package org.test.bean.param;
public class PersonParam {
private Integer id;
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
}
第二步,获得查询条件,封装查询条件处理,拼接sql
封装PageWhere<T>,创建文件
package org.test.bean.param;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class PageWhere<T> {
private String where;
public PageWhere(){
}
public String getWhere(){
return where;
}
public void setWhere(T str){
if(null != str){
if("String".equals(str.getClass().getSimpleName())){
where = ""+str;
}else{
where = transBean2Map(str);
}
}else{
where = " 1=1 ";
}
}
public static String transBean2Map(Object obj) {
if(obj == null){
return " 1=1 ";
}
String str = " 1=1 ";
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
if(null != value){
str += " and "+key+"="+value;
}
}
}
} catch (Exception e) {
System.out.println("transBean2Map Error " + e);
}
return str;
}
}
第四步,封装返回数据
封装Page <T>
package org.test.base.bean;
import java.util.ArrayList;
import java.util.List;
import org.test.bean.param.PageParam;
public class Page <T>{
private Integer page = 1; //当前页
private Integer size = 5;//每页默认为5
private Integer max; //最大页数
private Integer count; //项目条数
private List<Integer> indexs;//要显示的页码
private Integer indexNum ;//可现实页码范围内的数量
private List<T> list;
public Page() {
page = 1;
size = 5;
indexNum = 100;
}
public void getPageParam(PageParam<?> param){
page = param.getPage();
size = param.getSize();
}
/**
* 计算显示的导航页码
*/
private void count() {
Integer page = getPage();
Integer max = getMax();
if ( page!=null && max!=null ) {
int begin = Math.max(page-indexNum, 1);
int end = Math.min(page+indexNum, max);
indexs = new ArrayList<>();
for( int i = begin ; i <= end ; i++ ) {
indexs.add(i);
}
}
}
public void setPage(Integer page) {
this.page = page;
count(); //计算页码
}
public void setMax(Integer max) {
this.max = max;
count(); //计算页码
}
/**
* @return the size
*/
public Integer getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(Integer size) {
this.size = size;
}
/**
* @return the count
*/
public Integer getCount() {
return count;
}
/**
* @param count the count to set
*/
public void setCount(Integer count) {
this.count = count;
}
/**
* @return the indexs
*/
public List<Integer> getIndexs() {
return indexs;
}
/**
* @param indexs the indexs to set
*/
public void setIndexs(List<Integer> indexs) {
this.indexs = indexs;
}
/**
* @return the indexNum
*/
public Integer getIndexNum() {
return indexNum;
}
/**
* @param indexNum the indexNum to set
*/
public void setIndexNum(Integer indexNum) {
this.indexNum = indexNum;
}
/**
* @return the page
*/
public Integer getPage() {
return page;
}
/**
* @return the max
*/
public Integer getMax() {
return max;
}
/**
* @return the list
*/
public List<T> getList() {
return list;
}
/**
* @param list the list to set
*/
public void setList(List<T> list) {
this.list = list;
}
}
第五步,修改mapping
1.修改IBaseMapper.java
//添加俩个方法
List<HashMap<Object, Object>> queryByPage(@Param("name")String name, @Param("page")Integer page, @Param("size")Integer size,@Param("where")String where);
int queryCount( @Param("name")String lowerCase , @Param("where")String where);
2.修改IBaseMapper.xml
<select id="queryByPage" resultType="hashmap">
select * from ${name} where ${where} limit #{page},#{size}
</select>
<select id="queryCount" resultType="
select count(1) from ${name} where ${where}
</select>
第六步,修改Dao
修改IBaseDao.java
//添加四个方法
@SuppressWarnings("unchecked")
public Page<T> queryByPage(PageParam<?> pageParam,String where) {
String name = commonClass.getSimpleName().toLowerCase();
List<T> list = new ArrayList<>();
Page<T> page = new Page<>();
page.getPageParam(pageParam);
//分页 查询 数据 (表名,分页起始位置(利用mysql的limit),每页条数,[条件])
Class<M> clazz = (Class<M>) getBaseMapper().getClass();
Method queryByPage = null;
List<HashMap<Object, Object>> listmap = null;
try {
queryByPage = clazz.getDeclaredMethod("queryByPage",name.getClass(),Integer.class,Integer.class,String.class);
listmap = (List<HashMap<Object, Object>>) queryByPage.invoke(getBaseMapper(),name, (page.getPage()-1)*page.getSize(),page.getSize(),where);
} catch (ReflectiveOperationException e) {
throw new RuntimeException("数据读写异常", e);
}
// 遍历每个 Map 并通过自定义的方法转换成目标实体类,并添加到结果集list中
for (HashMap<Object, Object> hashMap : listmap) {
T t1 = hashMapToEntity(hashMap);
list.add( t1 );
}
//将转换好的数据集合放入 Page 对象
page.setList(list);
//根据条件查询数据条数
if ( where == null || where.length()<=0 ) {
page.setCount( queryCount());
}else {
page.setCount( queryCount(where));
}
//数据总条数
int tmp = page.getCount()/page.getSize();
//最大页数
page.setMax(page.getCount()<=page.getSize()?1:page.getCount()%page.getSize()>0?tmp+1:tmp);
return page;
}
/**
* 将HashMap 转成 实体类对象
*/
private T hashMapToEntity( Map<Object, Object> map ) {
T t = null;
try {
t = commonClass.newInstance();
for (Field f : t.getClass().getDeclaredFields()) {
f.setAccessible(true);
f.set(t,map.get(f.getName()));
}
} catch (Exception e1) {
e1.printStackTrace();
}
return t;
}
//无条件查询记录数
@SuppressWarnings("unchecked")
public int queryCount() {
String name = commonClass.getSimpleName().toLowerCase();
Class<M> clazz = (Class<M>) getBaseMapper().getClass();
Method queryCount = null;
try {
queryCount = clazz.getDeclaredMethod("queryCount",name.getClass(),String.class);
return (int) queryCount.invoke(getBaseMapper(),name, "1=1");
} catch (ReflectiveOperationException e) {
throw new RuntimeException("数据读写异常", e);
}
}
//有条件的查找记录数
@SuppressWarnings("unchecked")
public int queryCount(String where) {
String name = commonClass.getSimpleName().toLowerCase();
Class<M> clazz = (Class<M>) getBaseMapper().getClass();
Method queryCount = null;
try {
queryCount = clazz.getDeclaredMethod("queryCount",name.getClass(),String.class);
return (int) queryCount.invoke(getBaseMapper(),name,where);
} catch (ReflectiveOperationException e) {
throw new RuntimeException("数据读写异常", e);
}
}
第七步,修改service层
1.修改PersonService.java
//添加
ServerResponse<Page<Person>> queryByPage(PageParam<PersonParam> pageParam);
2.修改PersonServiceImpl.java
//添加方法
@Override
public ServerResponse<Page<Person>> queryByPage(PageParam<PersonParam> pageParam) {
// TODO Auto-generated method stub
PageWhere<PersonParam> pw = new PageWhere<PersonParam>();
pw.setWhere(pageParam.getParam());
Page<Person> list = personDao.queryByPage(pageParam,pw.getWhere());
if (list.getCount()>0){
return ServerResponse.createBySuccess(list);
}
return ServerResponse.createByError("查询记录为空");
}
第八步,修改controller层
修改PersonController.java
//添加方法
@RequestMapping("/queryByPage")
@ResponseBody
public ServerResponse<Page<Person>> queryByPage(@RequestBody PageParam<PersonParam> pageParam) {
return personService.queryByPage(pageParam);
}
到这后台封装完成了。。。。。。
第九步,修改前端页面,测试
直接给Home页面有注释
<template>
<div>
<div>
<button @click="getValue" style="height:30px;width:60px">点击</button>
<button @click="getValue2" style="height:30px;width:120px">封装数据点击</button>
<button @click="getValue3" style="height:30px;width:120px">base数据点击</button>
<button @click="queryByPage" style="height:30px;width:150px">basePage数据点击</button>
</div>
<div>
<div v-if="null != persons" style="font-size:36px;font-weigth: 600;">----未封装数据----</div>
<div v-for="value,key,index in persons" style="font-size:36px;font-weigth: 600;">{{value.name}}</div>
<div v-if="null != param" style="font-size:36px;font-weigth: 600;">----封装后数据----</div>
<div v-for="value,key,index in param" style="font-size:36px;font-weigth: 600;">姓名:{{value.name}} 年龄:{{value.age}}</div>
<div v-if="null != param3" style="font-size:36px;font-weigth: 600;">----base数据----</div>
<div v-for="value,key,index in param3" style="font-size:36px;font-weigth: 600;">姓名:{{value.name}} 年龄:{{value.age}}</div>
<div v-if="null != param4" style="font-size:36px;font-weigth: 600;">----basePage数据----</div>
<div v-for="value,key,index in param4" style="font-size:36px;font-weigth: 600;">姓名:{{value.name}} 年龄:{{value.age}}</div>
</div>
</div>
</template>
<script>
export default {
name: 'home',
data(){
return{
persons:null,
param:null,
param3:null,
param4:null
}
},
methods:{
getValue(){
var _that = this;
this.axios({
method:'post',
url:'/ownkua/own/personController/showPerson2',
data:{
id:1
}
}).then(function(response) {
_that.persons = response.data;
}).catch(function (error) {
console.log(error);
});
},
getValue2(){
var _that = this;
this.axios({
method:'post',
url:'/ownkua/own/personController/show',
data:{
}
}).then(function(response) {
_that.param = response.data.param;
}).catch(function (error) {
console.log(error);
});
},
getValue3(){
var _that = this;
this.axios({
method:'post',
url:'/ownkua/own/personController/show3',
data:{
}
}).then(function(response) {
_that.param3 = response.data.param;
}).catch(function (error) {
console.log(error);
});
},
queryByPage(){
var _that = this;
this.axios({
method:'post',
dataType: 'json',
url:'/ownkua/own/personController/queryByPage',
data:{
"page":1,
"size":6,
"param":{
"id":1
}
}
}).then(function(response) {
_that.param4 = response.data.param.list;
}).catch(function (error) {
console.log(error);
});
}
}
}
</script>
测试结果:只查到id是1的那条数据。
谢谢,实现没毛病,结束。。。。后面看看log配置了。