SpringMVC--請求資料對映

BtWangZhi發表於2018-01-10

1.1 將路徑中的資料對映到形參中

/**
     * 測試@PathVariable
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/pathVariable/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object pathVariable(@PathVariable("id") Integer id) {
        return id;
    }

請求示例:

/**
     * 測試@PathVariable
     */
    public static void testPathVariable() {
        String url = "http://localhost:81/test/pathVariable/1";
        String result = HttpClientUtil.doGet(url, null);
        System.out.println(result);
    }

1.2 get請求將鍵值對對映到方法形參中

/**
     * 測試get請求@pathParam
     * 
     * @param a
     * @param b
     * @return
     */
    @RequestMapping(value = "/getPathParam", method = RequestMethod.GET)
    @ResponseBody
    public Object requestParamGet(@PathParam("a") String a, @PathParam("b") String b) {
        return a + b;
    }

示例請求:

public static void testDoGetPathParam() {
        // 引數資訊
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("a", "a");
        param.put("b", "b");
        String url = "http://localhost:80/test/getPathParam";
        String result = HttpKitUtil.doGet(url, param);
        System.out.println(result);
    }

2 將鍵值對對映到Map中

/**
     * 測試@RequestParam
     * 
     * @param param
     * @return
     */
    @RequestMapping(value = "requestParam", method = RequestMethod.POST)
    @ResponseBody
    public Object requestParam(@RequestParam Map<String, Object> param) {
        return param;
    }

請求示例:

/**
     * 測試@RequestParam
     */
    public static void testRequestParam() {
        String url = "http://localhost:81/test/requestParam";
        Map<String, String> param = new HashMap<String, String>();
        param.put("a", "1");
        param.put("b", "2");
        param.put("c", "3");
        System.out.println(HttpClientUtil.doPostForm(url, param));
    }

3 將JSON資料對映到物件中

/**
     * 測試物件對映
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "user", method = RequestMethod.POST)
    @ResponseBody
    public Object user(@RequestBody User user) {
        return user;
    }

User類

public class User {

    private Integer id;

    private String name;

    private String password;
    //省略get和set

請求示例:

/**
     * 測試@RequestBody
     */
    public static void testRequestBody() {
        String url = "http://localhost:81/test/requestBody";
        Map<String, String> param = new HashMap<String, String>();
        param.put("a", "1");
        param.put("b", "2");
        param.put("c", "3");
        String strParam = JSONObject.toJSON(param).toString();
        System.out.println(HttpClientUtil.doPostJson(url, strParam));
    }

將Content-Type為application/json,傳送json資料對映到Map中:

@ResponseBody
    @RequestMapping(value = "/checkEndExpireDate", method = RequestMethod.POST)
    public Object checkContractExpire(HttpServletRequest request, HttpServletResponse response,
            @RequestBody Map<String, Object> mapParams) {

注意:
@RequestParam:適用於傳送頭ContentType為application/x-www-form-urlencoded,將鍵值對資料對映到Map中。
@RequestBody:適用於傳送頭ContentType不為application/x-www-form-urlencoded,將鍵值對資料對映到Map中
參考:http://blog.csdn.net/kobejayandy/article/details/12690161

4 將鍵值對對映到例項物件中:

    //測試物件對映
    @RequestMapping(value = "user", method = RequestMethod.POST)
    @ResponseBody
    public Object user(@RequestBody User user) {
        return user;
    }

請求示例:

    //測試對映到物件 
    public static void testUser() {
        String url = "http://localhost:81/test/user";
        JSONObject obj = new JSONObject();
        obj.put("id", 1);
        obj.put("name", "name");
        obj.put("password", "password");
        String str = obj.toJSONString();
        System.out.println(HttpClientUtil.doPostJson(url, str));
    }

5 從Request中獲取JSON資料

    //測試從Request中獲取JSON資料
    @RequestMapping(value = "getDataFromRequest", method = RequestMethod.POST)
    @ResponseBody
    public Object getDataFromRequest(HttpServletRequest request,
            HttpServletResponse response) {
        String result = "";
        try {
            String inputLine;
            while ((inputLine = request.getReader().readLine()) != null) {
                result += inputLine;
            }
            request.getReader().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

請求示例:

    //測試從Request中獲取資料    
    public static void testGetDataFromRequest() {
        String url = "http://localhost:81/test/getDataFromRequest";
        Map<String, String> param = new HashMap<String, String>();
        param.put("a", "1");
        param.put("b", "2");
        param.put("c", "3");
        String strParam = JSONObject.toJSON(param).toString();
        System.out.println(HttpClientUtil.doPostJson(url, strParam));
    }

6 傳遞XML資料

/**
     * 測試從Request中獲取資料
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "getDataFromRequest", method = RequestMethod.POST)
    @ResponseBody
    public Object getDataFromRequest(HttpServletRequest request, HttpServletResponse response) {
        String notityJson = "";
        String inputLine;
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityJson += inputLine;
            }
            logger.info(notityJson);

            @SuppressWarnings("unchecked")
            Map<String, Object> param = new XmlMapper().readValue(notityJson, HashMap.class);//xml轉為Map
            logger.info(param.toString());
            request.getReader().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return notityJson;
    }

Map轉為XML後請求,放回Xml後轉為Map。

Map<String, Object> param=new HashMap<String, Object>();
        param.put("a", "1");
        param.put("b", "2");
        param.put("c", "3");
        String strParam = convertMapToXml(param);//Map轉為XML
        System.out.println("Map轉為XML後:"+strParam);
        String resultXmlData = HttpClientUtil.doPostXml("http://localhost:80/test/getDataFromRequest", convertMapToXml(param));
System.out.println("xml轉Map後:"+convertXmlToMap(resultXmlData));//Xml轉Map

HttpClientUtil工具類中的靜態方法可以參考:http://blog.csdn.net/btwangzhi/article/details/79029350
Map與Xml之間的轉換可參考
http://blog.csdn.net/BtWangZhi/article/details/55121815

相關文章