首页 > 编程语言 > 详细

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

时间:2015-02-03 19:16:33      阅读:1062      评论:0      收藏:0      [点我收藏+]

内容如题

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 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 }


2.取值

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

 

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

原文:http://www.cnblogs.com/havery/p/4270542.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!