spring http 请求的数据传输的几种格式

/*
请求格式:url?参数1=值1&参数2=值2...
同时适用于GET和POST方式
spring 处理查询参数的方法又有几种写法
*/
public class HttpTestApi {
    //方法参数名和请求参数名可以不一样,通过@RequestParam注解来绑定参数
    @RequestMapping(value = "/test_1", method = RequestMethod.GET)
    public String testApi_1(@RequestParam("username") String un, @RequestParam("password") String pw)
    {
        return "hi,this is a test api " + un + "," + pw;
    }

    @RequestMapping(value = "/test_2", method = RequestMethod.GET)
    public String testApi_2(String username,String password)
    {
        return "hi,this is a test api " + username + "," + password;
    }

    @RequestMapping(value = "/test_3", method = RequestMethod.GET)
    public String testApi_3(HttpServletRequest request)
    {
        return "hi,this is a test api " + request.getParameter("username")
                + "," + request.getParameter("password");
    }

    @RequestMapping(value = "/test_4", method = RequestMethod.GET)
    public String testApi_4(UserVO user)
    {
        return "hi,this is a test api " + user.getUsername() +  "," + user.getPassword();
    }

    // 表单参数
    @RequestMapping(value = "/test_5", method = RequestMethod.POST)
    public String testApi_5(String username, String password) {
        return "hi,this is a test api " + username + "," + password;
    }

    //路径参数
    @RequestMapping(value = "/test_6/{username}/{password}", method = RequestMethod.GET)
    public String testApi_6(@PathVariable String username, @PathVariable String password) {
        return "hi,this is a test api " + username + "," + password;
    }

    //下面是 json 对象
    //需要添加请求头:Content-Type: application/json;charset=UTF-8
    //适用于POST方式
    @RequestMapping(value = "/test_7", method = RequestMethod.POST)
    public String testApi_7(@RequestBody UserVO user) {
        String username = user.getUsername();
        String password = user.getPassword();
        return "hi,this is a test api " + username + "," + password;
    }

    @RequestMapping(value = "/test_8", method = RequestMethod.POST)
    public String testApi_8(@RequestBody JSONObject json) {
        return "hi,this is a test api " + json.getString("username")
                + "," + json.getString("password");
    }

    @RequestMapping(value = "/test_9", method = RequestMethod.POST)
    public String testApi_9(@RequestBody Map userMap) {
        return "hi,this is a test api " + userMap.get("username")
                + "," + userMap.get("password");
    }

}

你可能感兴趣的:(JAVA,java,RequestMethod)