spring MVC 获取请求体

spring  MVC中如何获取请求体呢?

在spring MVC中如何获取请求要素呢?

通过如下方法:

Java代码  

  1. /** 
  2.      * Compatible with GET and POST 
  3.      *  
  4.      * @param request 
  5.      * @return : <code>String</code> 
  6.      * @throws IOException 
  7.      */  
  8.     public static String getRequestQueryStr(HttpServletRequest request,  
  9.             String charEncoding) throws IOException {  
  10.         String submitMehtod = request.getMethod();  
  11.         if (submitMehtod.equalsIgnoreCase("post")) {  
  12.             byte[] bytes = getRequestPostBytes(request);  
  13.             String charEncoding2 = request.getCharacterEncoding();// charset  
  14.             System.out.println("[getRequestQueryStr]charEncoding:"  
  15.                     + charEncoding2);  
  16.             System.out.println("[getRequestQueryStr]Content-Type:"  
  17.                     + request.getHeader(Constant2.REQUEST_HEADER_CONTENT_TYPE));  
  18.   
  19.             if(ValueWidget.isNullOrEmpty(charEncoding)){  
  20.                 charEncoding=SystemHWUtil.CHARSET_UTF;  
  21.             }  
  22.             return new String(bytes, charEncoding);  
  23.         } else {// form method :Get  
  24.             return request.getQueryString();  
  25.         }  
  26.     }  

 对GET请求的参数是没有问题的,但是对于POST请求获取不到为什么呢?

因为spring MVC已经获取了一遍request的stream,所以再次获取时是为空的,(这是输入流的特性,可以查查官网API),所以我获取到request 的InputStream之后调用reset,但是报错,不支持reset操作.

怎么办呢?

在spring MVC 的控制器中使用@RequestBody 注解,作用是获取请求体,格式是字节数组,见代码

Java代码  

  1. @ResponseBody  
  2.     @RequestMapping(value = "/jsonStub", produces = SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF)  
  3.     public String json(Model model, HttpSession session,@RequestBody byte[]bytes,  
  4.             HttpServletRequest request, String callback) throws IOException {  
  5.         Map map=WebServletUtil.parseRequest(request, null);  
  6.         if(ValueWidget.isNullOrEmpty(map)){  
  7.             String postStr=new String(bytes,SystemHWUtil.CURR_ENCODING);//username=huangwei&password=123  
  8.             System.out.println("postStr:"+postStr);//username=%E9%BB%84%E5%A8%81&password=123  
  9.             postStr=URLDecoder.decode(postStr,SystemHWUtil.CURR_ENCODING);//{"username":"黄威","password":"123"}  
  10.             map=WebServletUtil.parseRequestStr(postStr, true);  
  11.         }  
  12.         String content = HWUtils.getJsonP(map, callback);  
  13.         return content;  
  14.     }  

 

@RequestBody后紧跟的参数将被注入请求体的字节数组(spring mVC帮我们完成的).

注意:request.getInputStream() 读取一次之后,再次读取就读取不到

上述代码依赖的方法:

Java代码  

  1. /*** 
  2.      * Get request query string, form method : post 
  3.      *  
  4.      * @param request 
  5.      * @return byte[] 
  6.      * @throws IOException 
  7.      */  
  8.     public static byte[] getRequestPostBytes(HttpServletRequest request)  
  9.             throws IOException {  
  10.         int contentLength = request.getContentLength();  
  11.         /*当无请求参数时,request.getContentLength()返回-1 */  
  12.         if(contentLength<0){  
  13.             return null;  
  14.         }  
  15.         byte buffer[] = new byte[contentLength];  
  16.         for (int i = 0; i < contentLength;) {  
  17.   
  18.             int readlen = request.getInputStream().read(buffer, i,  
  19.                     contentLength - i);  
  20.             if (readlen == -1) {  
  21.                 break;  
  22.             }  
  23.             i += readlen;  
  24.         }  
  25.         return buffer;  
  26.     }  
  27.   
  28.     /*** 
  29.      * Get request query string, form method : post 
  30.      *  
  31.      * @param request 
  32.      * @return 
  33.      * @throws IOException 
  34.      */  
  35.     public static String getRequestPostStr(HttpServletRequest request)  
  36.             throws IOException {  
  37.         byte buffer[] = getRequestPostBytes(request);  
  38.         String charEncoding = request.getCharacterEncoding();  
  39.         if (charEncoding == null) {  
  40.             charEncoding = "UTF-8";  
  41.         }  
  42.         return new String(buffer, charEncoding);  
  43.     }  

 

参考:http://json20080301.iteye.com/blog/1874074?utm_source=tuicool

时间: 2024-08-06 22:02:43

spring MVC 获取请求体的相关文章

spring MVC接收请求体总是多一个等号

spring MVC接收请求体总是多一个等号 比如我发送的请求体是字符串aaa spring MVC 接收到的是aaa= 接口如下: /*** * @param requestInfoBean * @return */ @RequestMapping(value = "/ajax", produces = SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF) @ResponseBody public String ajax(@RequestBody S

Java Spring Controller 获取请求参数的几种方法详解_java

Java Spring Controller 获取请求参数的几种方法  1.直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交.若"Content-Type"="application/x-www-form-urlencoded",可用post提交        url形式:http://localhost:8080/SSMDemo/demo/addUser1?username=lixiaoxi&pas

图片- uploadify 带一个值上传文件,JAVA spring MVC 获取不到值?

问题描述 uploadify 带一个值上传文件,JAVA spring MVC 获取不到值? $(document).ready( function() { $('#file_upload').uploadify( { 'swf' : '${root}uploadify/uploadify.swf',//上传按钮的图片,默认是这个flash文件 'uploader' : '${root}importFile', //上传所处理的服务器 'cancelImg' : 'uploadfiy/uploa

java web获取请求体内容

Java Web中如何获取请求体内容呢? 我们知道请求方式分为两种:Get,Post Java代码   /***       * Compatible with GET and POST       *        * @param request       * @return : <code>byte[]</code>       * @throws IOException       */       public static byte[] getRequestQuery

spring mvc ajax请求数据后,前台根据返回的key如果跳转的别的jsp界面

问题描述 spring mvc ajax请求数据后,前台根据返回的key如果跳转的别的jsp界面 根据返回的data,在jsp前端进行跳转,有没有好的办法,还是可以通过配置就可以实现: window.location不太好使,可以跳转但是URL地址会显示具体的参数: 解决方案 参数你都放action里面了...那肯定显示了..fm表单放一个隐藏域存储你的cardList参数 <form id="fm" action="${}.../cardlist">&

j2ee框架-spring mvc控制请求跳转

问题描述 spring mvc控制请求跳转 springmvc控制请求跳转,全部配置在配置文件中,不在类里面写哪个请求返回到哪个页面和 比如hello.do请求过来返回到index.jsp 我在一个xml文件中配置这些信息 解决方案 spring MVC 跳转spring-mvc 跳转Spring MVC 跳转相关---------------------- 解决方案二: 用XML配置没有使用注解来得快.如下 @RequestMapping("/hello.do") public St

spring mvc设置应答体的content type

spring MVC中如何设置应答体的content type呢? spring MVC中如何设置返回类型呢? 我们知道response 的content type主要有: text/html text/plain application/json;charset=UTF-8 application/octet-stream 等 先举一个例子,spring mvc中可以通过如下方式返回json字符串: Java代码   @ResponseBody       @RequestMapping(va

spring MVC request请求不能传递带逗号的参数

问题描述 代码如下<html>  <body>    <input name="test" value="12,34,56" type="checkbox"/>    <input name="test" value="78,90,11" type="checkbox"/>  </body></html> 接收参数类

关于spring mvc映射请求的问题

问题描述 @RequestMapping(value="/**/*.*",method=RequestMethod.GET)publicStringdynamic(HttpServletRequestrequest,HttpServletResponseresponse,ModelMapmodel){String[]paths=URLHelper.getPaths(request);intlen=paths.length;if(len==1){returnnull;}elseif(le