Spring拦截器从Request中获取Json格式的数据

 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 havery
23 */
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 @Override
58 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 @Override
69 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 }
Spring拦截器从Request中获取Json格式的数据

2.取值

MyRequestWrapper myRequestWrapper = new MyRequestWrapper((HttpServletRequest) request);
String body = myRequestWrapper.getBody();

2、继承HttpServletRequestWrapper 和HttpServletResponse 两个类对 getParameter(String str) 和getWrite()两方法进行重写,而方法中实现我们想要的操作

3、使用Filter过滤器,我们知道Filter是在请求到达servlet之前和servlet响应信息到达浏览器之前进行两次拦截,而就在到达server之前我们将FilterChain的doFilter(request,reponse)方法的request参数替换为我们装饰后的request而我们又重写的getParameter(String str)方法,之后调用的就是这个方法,因此也就完成了

请求参数的过滤和修改

4、响应和请求其实是一样的,也是替换了Response对象,从而调用我们重写的方法实

上一篇:中文格式python 打印json格式的数据中文显示问题


下一篇:实现android上解析Json格式数据功能