天天看點

restful RequestMapping POST\PUT 示例&要點

@RequestMapping(value = "/xxx/xxxxxx", method = RequestMethod.POST)
public Response fun1(HttpServletRequest request, 
      @PathVariable("paraA") String a, 
      @RequestParam("ParaB") String b, 
      @RequestParam("ParaC") String c ) {
    
    //code here
    
    return response;
}  

@RequestMapping(value = "/xxx/yyyyyyy", method = RequestMethod.PUT)
public Response fun2(HttpServletRequest request, 
      @PathVariable("paraA") String a, 
      @RequestParam("ParaB") String b, 
      @RequestParam("ParaC") String c ) {

    //code here
    
    return response;
  }      

要點:

@RequestParam 

A) 常用來處理簡單類型的綁定,通過Request.getParameter() 擷取的String可直接轉換為簡單類型的情況( String--> 簡單類型的轉換操作由ConversionService配置的轉換器來完成);因為使用request.getParameter()方式擷取參數,是以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值;

B)用來處理Content-Type: 為 ​

​application/x-www-form-urlencoded​

​編碼的内容,送出方式GET、POST;

C) 該注解有兩個屬性: value、required; value用來指定要傳入值的id名稱,required用來訓示參數是否必須綁定;

*如果是json,則要以下寫法:

@RequestMapping(value = "/api/xxxx/{param}", method = { RequestMethod.PUT })
public Response fun3(
      @PathVariable(value = "param") String param,
      HttpServletRequest request) {
    logger.info("============= API start ==================");
    //code service here

    logger.info("=============  API end ==================");
    return response;
  }      
JSONObject json = ParametersUtil.getRequestBodyWithJson(param,request);      
public class ParametersUtil {

  private static final Logger logger = LoggerFactory
      .getLogger(ParametersUtil.class);

  public static JSONObject getRequestBodyWithJson(String parameter,
      HttpServletRequest request) {
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(
          request.getInputStream()));
      String line = null;
      StringBuilder sb = new StringBuilder();
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }
      logger.info("Request Body:" + sb.toString());

      String reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
      JSONObject json = new JSONObject(reqBody);

      logger.info(
          "[getRequestBodyWithJson][{}]-- get request body with json successfully",
          parameter);
      return json;
    } catch (Exception e) {
      logger.error(
          "[getRequestBodyWithJson][{}]-- get request body with json fail, exception is [{}]",
          parameter, e.getMessage());
      return null;
    }

  }

  public static JSONArray getJsonArray(JSONObject jsonObject, String key) {
    try {
      if (jsonObject == null) {
        return null;
      } else {
        return jsonObject.getJSONArray(key);
      }
    } catch (Exception e) {
      return null;
    }
  }

  public static String covertJSONArray2String(JSONArray jsonArray) {
    if (jsonArray == null || jsonArray.length() == 0) {
      return null;
    }
    List<String> list = new ArrayList<String>();
    for (int i = 0; i < jsonArray.length(); i++) {
      String s = (String) jsonArray.get(i);
      if (s != null && !s.isEmpty()) {
        list.add(s.trim());
      }
    }
    if (list.isEmpty()) {
      return null;
    } else {
      return list.toString().replace("[", "").replace("]", "")
          .replace(" ", "");
    }
  }

  public static String getJsonValue(JSONObject jsonObject, String key) {
    try {
      if (jsonObject == null) {
        return null;
      } else {
        return jsonObject.getString(key);
      }
    } catch (Exception e) {
      return null;
    }
  }

  public static JSONObject getJsonObject(JSONObject jsonObject, String key) {
    try {
      if (jsonObject == null) {
        return null;
      } else {
        return jsonObject.getJSONObject(key);
      }
    } catch (Exception e) {
      return null;
    }
  }
}