过滤器中获取json数据
判断是不是 json请求
//获取json
HttpServletRequest request = (HttpServletRequest) servletRequest;
String contentType = request.getContentType();
String paramJson = "";
if ("application/json; charset=UTF-8".equals(contentType)) {
paramJson = this.getJsonParam((HttpServletRequest) servletRequest);
}
获取json数据
/**
* 获取Json数据
*
* @param request
* @return
*/
private String getJsonParam(HttpServletRequest request) {
String jsonParam = "";
ServletInputStream inputStream = null;
try {
int contentLength = request.getContentLength();
if (!(contentLength < 0)) {
byte[] buffer = new byte[contentLength];
inputStream = request.getInputStream();
for (int i = 0; i < contentLength; ) {
int len = inputStream.read(buffer, i, contentLength);
if (len == -1) {
break;
}
i += len;
}
jsonParam = new String(buffer, "utf-8");
}
} catch (IOException e) {
log.error("参数转换成json异常g{}", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error("参数转换成json异常s{}", e);
}
}
}
return jsonParam;
}
返回json
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
String result = "";
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (Exception e) {
e.printStackTrace();
} finally {
writer.print(result);
writer.flush();
writer.close();
}
来源:CSDN
作者:你笑的像一条狗
链接:https://blog.csdn.net/weixin_38361347/article/details/104502997