獲取get,post請求參數,並驗證是否爲空工具類
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author xnz
* @date 2019/10/17 9:55
*/
public class ParamVerify {
/**
* 獲取post方式傳入的參數並根據傳入的需驗證的參數進行驗證
* @param params 需判斷是否爲空的參數
* @return
* @throws IOException
*/
public static Map<String, Object> verifyPostParam(String ... params) throws IOException {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
//轉換爲map
JSONObject paramsMap = JSONObject.parseObject(sb.toString());
// 驗證參數不爲空
if(paramsMap != null) {
for (String param : params) {
String paramValue = (String) paramsMap.get(param);
if (StringUtils.isBlank(paramValue)) {
//需判斷的參數爲空,拋出異常
throw new RuntimeException("請求參數錯誤! " + param + " 不能爲空!");
}
}
}else{
throw new RuntimeException("請求參數錯誤!");
}
return paramsMap;
}
/**
* 將request.getParameterMap()方式獲取的參數整理並根據傳入的需驗證的參數進行驗證
* @param parameterMap 需整理的參數集合
* @param params 需判斷是否爲空的參數
* @return
*/
public static Map<String,String> verifyGetParam(Map<String, String[]> parameterMap,String ... params){
Map<String,String> paramsMap = new HashMap<String, String>();
if(parameterMap.isEmpty()){
throw new RuntimeException("請求參數錯誤!");
}
Set<String> keys = parameterMap.keySet();
for (String param : keys) {
String[] values = parameterMap.get(param);
paramsMap.put(param,values[values.length-1]);
}
for (String param : params) {
String paramValue = paramsMap.get(param);
if(StringUtils.isBlank(paramValue)){
//需判斷的參數爲空,拋出異常
throw new RuntimeException("請求參數錯誤! " + param + " 不能爲空!");
}
}
return paramsMap;
}
}