首页 > 代码库 > Spring拦截器从Request中获取Json格式的数据
Spring拦截器从Request中获取Json格式的数据
内容如题
1.创建取值类
1 /** 2 * MyRequestWrapper.java 3 * 4 * @screen 5 * @author havery 6 */ 7 package com.newpp.core.interceptor; 8 9 import java.io.BufferedReader;10 import java.io.ByteArrayInputStream;11 import java.io.IOException;12 import java.io.InputStream;13 import java.io.InputStreamReader;14 15 import javax.servlet.ServletInputStream;16 import javax.servlet.http.HttpServletRequest;17 import javax.servlet.http.HttpServletRequestWrapper;18 19 /**20 * MyRequestWrapper.21 * 22 * @author havery23 */24 public class MyRequestWrapper extends HttpServletRequestWrapper {25 private final String body;26 27 public MyRequestWrapper(HttpServletRequest request) throws IOException {28 super(request);29 StringBuilder stringBuilder = new StringBuilder();30 BufferedReader bufferedReader = null;31 try {32 InputStream inputStream = request.getInputStream();33 if (inputStream != null) {34 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));35 char[] charBuffer = new char[128];36 int bytesRead = -1;37 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {38 stringBuilder.append(charBuffer, 0, bytesRead);39 }40 } else {41 stringBuilder.append("");42 }43 } catch (IOException ex) {44 throw ex;45 } finally {46 if (bufferedReader != null) {47 try {48 bufferedReader.close();49 } catch (IOException ex) {50 throw ex;51 }52 }53 }54 body = stringBuilder.toString();55 }56 57 @Override58 public ServletInputStream getInputStream() throws IOException {59 final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());60 ServletInputStream servletInputStream = new ServletInputStream() {61 public int read() throws IOException {62 return byteArrayInputStream.read();63 }64 };65 return servletInputStream;66 }67 68 @Override69 public BufferedReader getReader() throws IOException {70 return new BufferedReader(new InputStreamReader(this.getInputStream()));71 }72 73 public String getBody() {74 return this.body;75 }76 }
2.取值
MyRequestWrapper myRequestWrapper = new MyRequestWrapper((HttpServletRequest) request); String body = myRequestWrapper.getBody();
Spring拦截器从Request中获取Json格式的数据
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。