@pathvariable 与@requestparam 写rest接口时遇到的
@pathvariable 代码如下:
1 2 3 4 5 6 7 8 9 10 11 | @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(); } |
测试:
1 2 3 4 5 6 7 8 9 10 11 | @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 代码如下:
1 2 3 4 5 6 7 8 9 10 11 | @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(); } |
测试
1 2 3 4 5 6 7 8 9 | @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..." ); } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步