request.getInputStream()1回しか読み込めないソリューション
3517 ワード
, , json , , request.getInputStream(), controller , , request.getInputStream() 。 。 , 。 ,
1: RequestHelper , , Map, 。
public class RequestHelper{
/**
* @param request
* @return
*/
private static Logger logger = LoggerFactory.getLogger(RequestHelper.class);
public static Map getBodyString(ServletRequest request) {
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = request.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
logger.warn("getBodyString !");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return JSON.parseObject(sb.toString(),Map.class);
}
}
2: inputStream , , , HttpServletRequestWrapper 。
public class EbHttpServletWrapper extends HttpServletRequestWrapper {
private Logger logger = LoggerFactory.getLogger(EbHttpServletWrapper.class);
private String encoding = "UTF-8";
private byte[] requestBodyIniBytes;
public EbHttpServletWrapper(HttpServletRequest request) throws IOException {
super(request);
ServletInputStream stream = request.getInputStream();
String requestBody = StreamUtils.copyToString(stream, Charset.forName(encoding));
requestBodyIniBytes = requestBody.getBytes(encoding);
}
public ServletInputStream getInputStream() {
final ByteArrayInputStream in;
in = new ByteArrayInputStream(requestBodyIniBytes);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return in.read();
}
};
}
}
3:フィルタに次のコードを追加します(ファイルタイプの場合、問題が発生する可能性があります.削除し、ブロックしません).public class RequestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest) request;
if(Objects.isNull(request1.getHeader("Content-Type")) || request1.getHeader("Content-Type").contains("multipart/form-data;")){
chain.doFilter(request,response);
}else {
chain.doFilter(new EbHttpServletWrapper(request1), response);
}
}
@Override
public void destroy() {
}
}
転送されたデータがjson形式で行われていない場合は、このような操作をする必要はなく、request.getParameter(「key」)を直接使用すればよい.