本篇爲系列文,不以目的爲目的,以學習爲目的。旨在學習,重在研究。
最終版:SSM攔截器校驗JSON數據(3) -- 解決攔截器獲取json後,controller參數爲空
上一篇:設置攔截器
發送json數據格式
用postman發送json數據,注意這裏是raw-json方式,兩種不同方式會再談論。
這樣的數據在request中是以流的形式保存的,獲取流的方式就是getInputStream()
在攔截器中獲取以流形式存在的json數據
我要在項目到達controller之前做校驗,所以要在preHandle方法中寫邏輯
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
try{
//獲取request中的json數據
AccountInfo accountInfo = getParam(request);
//省略業務邏輯處理代碼
}catch catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*@Description: 解析request裏的AccountInfo
*/
public AccountInfo getParam(HttpServletRequest request) throws IOException, SSOException {
String jsonString = null;
String submitMethod = request.getMethod();
if("GET".equals(submitMethod) || submitMethod.equals("get")){
jsonString = getParamStringByGet(request);
}else if(submitMethod.equals("POST") || submitMethod.equals("post")){
jsonString = getParamJsonStringByPost(request);
}
if(StringUtils.isBlank(jsonString)){
return null;
}
//json字符串解析成對象
AccountInfo parse = JSONObject.parseObject(jsonString, AccountInfo.class);
return parse;
}
/**
*@Description: 解析post方式提交的json數據
*/
private String getParamJsonStringByPost(HttpServletRequest request) throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength; i++) {
int readlen = request.getInputStream().read(buffer,i,contentLength -i);
if(readlen == -1){
break;
}
i+=readlen;
}
return new String(buffer,"UTF-8");
}
/**
*@Description: 解析get方式提交的request參數
*/
private String getParamStringByGet(HttpServletRequest request) throws IOException {
return new String(request.getQueryString().getBytes("ios-8859-1"),"utf-8").replaceAll("%22", "\"");
}
存在問題:請求到達Controller後,參數爲空
原因:request中的數據流只能讀取一次。