springboot框架自动注入分页查询基础数据(自定义参数解析器)

硅谷探秘者 1696 0 0

        一般分页查询的接口都需要传入page(当前第几页),limit(限制行数)两个参数。如果框架本身没有做处理的话我们需要自己在控制层写参数去接收和处理这俩参数。如何配置基础框架,让其自动接收和处理这些参数呢?

        首先我们有一个基础的配置类BasePage,这个类里面只有page,limit,index这三个属性,我们在创建其他查询参数封装类的时候要继承BasePage这个类。然后用我们自己实现的参数解析器去解析和注入这些属性,来实现自动注入的目的。

案例:

BasePage:

//分页基类
//select * from a limit #{index},#{limmit} 
public class BasePage {
	private Integer page;//当前页
	private Integer limit;//限制行数
	private int index;// 当前位置
	public Integer getPage() {
		return page;
	}
	public void setPage(Integer page) {
		this.page = page;
	}
	public Integer getLimit() {
		return limit;
	}
	public void setLimit(Integer limit) {
		this.limit = limit;
	}
	public int getIndex() {
		return index;
	}
	public void setIndex(int index) {
		this.index = index;
	}
}

自定义参数解析器 

import java.lang.reflect.Field;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
//参数解析器
public class RequestPageHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    
	public boolean supportsParameter(MethodParameter methodParameter) {
        //该参数的类型是否继承了BasePage类,是的话进行参数封装
        return  methodParameter.getParameterType().getSuperclass()==BasePage.class;
    }
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
    	HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
    	Integer p = null;
		Integer l = null;
		try {
			p = new Integer(request.getParameter("page"));
			l = new Integer(request.getParameter("limit"));
		} catch (Exception e) {
			e.printStackTrace();
		}
    	Class<?> c=methodParameter.getParameterType();//参数类型
    	Object obj=c.newInstance();
    	if(p!=null) {
    		//注入分页参数
        	Field pf=c.getSuperclass().getDeclaredField("page");
        	pf.setAccessible(true);
        	pf.set(obj,p);
        	if(l!=null) {
        		Field lf=c.getSuperclass().getDeclaredField("limit");
            	lf.setAccessible(true);
            	lf.set(obj,l);
            	Field ifs=c.getSuperclass().getDeclaredField("index");
            	ifs.setAccessible(true);
            	ifs.set(obj,(p-1)*l);
        	}
    	}
    	//注入查询参数
    	Field[] fs=c.getDeclaredFields();
    	{
			String param;
	    	for(Field f:fs) {
	    		try {
					if((param=request.getParameter(f.getName()))!=null) {
						Object data = null;
						if(f.getType()==String.class) {
							data = param;
						}else if(f.getType()==Short.class || f.getType()==short.class) {
							data = new Short(param);
						}else if(f.getType()==Integer.class || f.getType()==int.class) {
							data = new Integer(param);
						}else if(f.getType()==Long.class || f.getType()==long.class) {
							data = new Long(param);
						}else if(f.getType()==Double.class || f.getType()==double.class) {
							data = new Double(param);
						}else if(f.getType()==Float.class || f.getType()==float.class) {
							data = new Float(param);
						}else if(f.getType()==Boolean.class || f.getType()==boolean.class) {
							data = new Boolean(param);
						}else if(f.getType()==Byte.class || f.getType()==byte.class) {
							data = new Byte(param);
						}
						if(data!=null) {
							f.setAccessible(true);
							f.set(obj, data);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
    	}
        return obj;
    }
}

配置参数解析器

import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new RequestPageHandlerMethodArgumentResolver());
    }
}

比如现在我们有一个分页接口,这个接口有一个我们定义的QueryUser参数,我们只需要让QueryUser这个类继承BasePage这个类,即可实现自动注入:

@RestController
@RequestMapping("test")
public class TestController {
	//测试
	@GetMapping
	public Map<String,QueryUser> test(QueryUser qu){
		System.out.println(qu);
		Map<String, QueryUser> map=new HashMap<String, QueryUser>();
		map.put("data",qu);
		return map;
	}
	
}

QueryUser

import example.test.config.BasePage;
//查询用户
public class QueryUser extends BasePage{
	private Integer id;
	private String userName;
	private int sex;
	private boolean px;
	@Override
	public String toString() {
		return "QueryUser [id=" + id + ", userName=" + userName + ", sex=" + sex + ", px=" + px + ", getPage()="
				+ getPage() + ", getLimit()=" + getLimit() + ", getIndex()=" + getIndex() + "]";
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	public boolean isPx() {
		return px;
	}
	public void setPx(boolean px) {
		this.px = px;
	}
}

如果你这样请求:http://localhost:8080/test?page=102&limit=1004&userName=sdfsdf&px=true&id=1231&sex=1 

会发现参数已经封装好了。


评论区
请写下您的评论...
暂无评论...
猜你喜欢
框架 2284 很多项目在开发的时候都会遇到的问题,一般主要用到两个page和limit,page是第几,limit是请求多少条。而一般在请求库的时候我们用不到page,用到的是用page
java 数据库 2609 java项目-库之间时进行交换服务(右上方下载)压缩包内附sql脚本,本项目为springboot+mybatis,导项目即可启测试。目的,实现两个进行同步,
java项目 1394 springboot+mybatis配置多源并利用aop实现切换(demo)
weblog 2175 vue使用v-model(双向)收集表单!DOCTYPEhtmlhtml head metacharset="UTF-8" title/title scriptsrc="js
框架 1610 springboot+mybatis配置多源并利用aop实现切换1.项目大致结构2.pom依赖dependencygroupIdorg.springframework.boot
算法基础,linux 4276 问题描述springboot项目在跨域名调用接口,并且需要传的请求头时报错:AccesstoXMLHttpRequestat'http://ydatestapi.libawall.com
java基础 3839 ,是对传输的总称或抽象。它的特性是进行传输。所以io流不仅仅用于文件内容的传输。接下来演示一下输出流并利用流的概念复制一个字符串,将字符串s中的内容流向s2。importjava.io.
official 1049 。netty提供了强大的编,使得我们编写的编很容易,也容易封装重用。对于Netty而言,编由两部组成:编码:负责将消息从字节或其他序列形式转成指的消息对象。编码
归档
2018-11  12 2018-12  33 2019-01  28 2019-02  28 2019-03  32 2019-04  27 2019-05  33 2019-06  6 2019-07  12 2019-08  12 2019-09  21 2019-10  8 2019-11  15 2019-12  25 2020-01  9 2020-02  5 2020-03  16 2020-04  4 2020-06  1 2020-07  7 2020-08  13 2020-09  9 2020-10  5 2020-12  3 2021-01  1 2021-02  5 2021-03  7 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。