com.kasinf.framework.rest.web.method.BaseMethodArgumentResolver Maven / Gradle / Ivy
package com.kasinf.framework.rest.web.method;
import org.springframework.lang.NonNull;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
/**
* @author 凯鸿
*
* 基础参数解析器
*/
public abstract class BaseMethodArgumentResolver implements HandlerMethodArgumentResolver {
/**
* 获取指定前缀的参数:包括uri variables 和 parameters
*
* @param namePrefix 参数前缀
* @param subPrefix 是否截取掉namePrefix的前缀
* @param request {@link NativeWebRequest}
* @return Map
*/
protected Map getPrefixParameterMap(String namePrefix, NativeWebRequest request, boolean subPrefix) {
Map result = new HashMap<>();
Map variables = getUriTemplateVariables(request);
int namePrefixLength = namePrefix.length();
for (String name : variables.keySet()) {
if (name.startsWith(namePrefix)) {
//page.pn 则截取 pn
if (subPrefix) {
char ch = name.charAt(namePrefix.length());
//如果下一个字符不是 数字 . _ 则不可能是查询 只是前缀类似
if (illegalChar(ch)) {
continue;
}
result.put(name.substring(namePrefixLength + 1), new String[]{variables.get(name)});
} else {
result.put(name, new String[]{variables.get(name)});
}
}
}
Iterator parameterNames = request.getParameterNames();
while (parameterNames.hasNext()) {
String name = parameterNames.next();
if (name.startsWith(namePrefix)) {
//page.pn 则截取 pn
if (subPrefix) {
char ch = name.charAt(namePrefix.length());
//如果下一个字符不是 数字 . _ 则不可能是查询 只是前缀类似
if (illegalChar(ch)) {
continue;
}
result.put(name.substring(namePrefixLength + 1), request.getParameterValues(name));
} else {
result.put(name, request.getParameterValues(name));
}
}
}
return result;
}
private boolean illegalChar(char ch) {
return ch != '.' && ch != '_' && !(ch >= '0' && ch <= '9');
}
protected final String getJsonString(NativeWebRequest webRequest){
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
StringBuilder sb = new StringBuilder();
try {
Objects.requireNonNull(request).getReader().lines().forEach(l->sb.append(l.trim()));
} catch (IOException ignore) {
}
return sb.toString();
}
@SuppressWarnings("unchecked")
protected final Map getUriTemplateVariables(@NonNull NativeWebRequest webRequest) {
// 获取url参数
return (Map) webRequest.getAttribute(
HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
}
}