@pathvariable 与@requestparam 写rest接口时遇到的

@pathvariable 代码如下:

@RequestMapping(value = "getModelCenterIp/{parameterType}")
public @ResponseBody String getModelCenterIp(@PathVariable("parameterType") String parameterType) {
	JSONArray json = new JSONArray();
	if (StringUtils.isNotBlank(parameterType)) {
		Parameter parameter = parameterService.findParameterByType(parameterType);
		JSONObject jo = new JSONObject();
		jo.put("mc_ft_path", parameter.getParameterValue());
		json.add(jo);
	}
	return json.toString();
	}

测试:

@Test
public void getModelCenterIp() {
	System.out.println("进入getModelCenterIp...");
//使用@PathVariable接收参数,参数值需要在url进行占位,如: String url = "http://192.168.0.115:8888/cmp/rest/parameter/getModelCenterIp/{parameterType}";
//前端传参的URL于后端@RequestMapping的URL必须相同且参数位置一一对应,否则前端会找不到后端地址 // 第一个参数是restful接口请求路径 第二个参数是响应的类型 String.class Map<String, String> map = new HashMap<String, String>(); map.put("parameterType", "upload_path"); String result =template.getForObject(url, String.class, map); System.out.println("输出结果:" + result); System.out.println("进入getModelCenterIp end..."); }

@requestparam  代码如下:

    @RequestMapping(value = "getModelCenterIp")
    public @ResponseBody String getModelCenterIp(@RequestParam("parameterType") String parameterType) {
           JSONArray json = new JSONArray();
           if (StringUtils.isNotBlank(parameterType)) {
                 Parameter parameter = parameterService.findParameterByType(parameterType);
                 JSONObject jo = new JSONObject();
                  jo.put("mc_ft_path", parameter.getParameterValue());
                  json.add(jo);
             }
           return json.toString();
     }

测试

     @Test
     public void getModelCenterIp() {
          System.out.println("进入getModelCenterIp...");
	  String url = "http://192.168.0.115:8888/cmp/rest/parameter/getModelCenterIp?parameterType=upload_path";
	  // 第一个参数是restful接口请求路径 第二个参数是响应的类型 String.class
	  String result = template.getForObject(url, String.class);
	  System.out.println("输出结果:" + result);
	  System.out.println("进入getModelCenterIp end...");
     }

  

原文地址:https://www.cnblogs.com/person008/p/7569083.html