国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

@PathVariable注解,讓spring支持參數帶值功能的案例

瀏覽:3日期:2023-07-22 13:34:12
@PathVariable的作用

獲取URL動態變量,例如

@RequestMapping('/users/{userid}') @ResponseBody public String getUser(@PathVariable String userid){ return 'userid=' + userid; }@PathVariable的包引用

spring自從3.0版本就引入了org.springframework.web.bind.annotation.PathVariable,

這是RESTful一個具有里程碑的方式,將springMVC的精華推向了高潮,那個時代,跟微信公眾號結合的開發如火如荼,很多東西都會用到URL參數帶值的功能。

@PathVariable的PathVariable官方doc解釋

- Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods in Servlet environments.

- If the method parameter is Map<String, String> or MultiValueMap<String, String> then the map is populated with all path variable names and values.

翻譯過來就是:

- 在SpringMVC中可以使用@PathVariable注解,來支持綁定URL模板參數(占位符參數/參數帶值)

- 另外如果controller的參數是Map(String, String)或者MultiValueMap(String, String),也會順帶把@PathVariable的參數也接收進去

@PathVariable的RESTful示范

前面講作用的時候已經有一個,現在再提供多一個,別人訪問的時候可以http://localhost:8080/call/窗口號-檢查編號-1

/** * 叫號 */ @PutMapping('/call/{checkWicket}-{checkNum}-{status}') public ApiReturnObject call(@PathVariable('checkWicket') String checkWicket,@PathVariable('checkNum') String checkNum, @PathVariable('status') String status) { if(StringUtils.isBlank(checkWicket) || StringUtils.isBlank(checkNum)) { return ApiReturnUtil.error('叫號失敗,窗口號,檢查者編號不能為空'); }else { if(StringUtils.isBlank(status)) status ='1'; try {lineService.updateCall(checkWicket,checkNum,status);return ApiReturnUtil.success('叫號成功'); } catch (Exception e) {return ApiReturnUtil.error(e.getMessage()); } } }

補充:解決@PathVariable接收參數帶點號時只截取點號前的數據的問題

問題:

@RequestMapping(value = 'preview/{fileName}', method = RequestMethod.GET)public void previewFile(@PathVariable('fileName') String fileName, HttpServletRequest req, HttpServletResponse res) { officeOnlinePreviewService.previewFile(fileName, req, res);}

本來fileName參數傳的是:userinfo.docx,

但結果接收到的是:userinfo

這顯然不是我想要的。

解決方法:

@RequestMapping(value = 'preview/{fileName:.+}', method = RequestMethod.GET)public void previewFile(@PathVariable('fileName') String fileName, HttpServletRequest req, HttpServletResponse res) { officeOnlinePreviewService.previewFile(fileName, req, res);}

參數fileName這樣寫,表示任何點(包括最后一個點)都將被視為參數的一部分:

{fileName:.+}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。

標簽: Spring
主站蜘蛛池模板: 卢龙县| 达州市| 吉木萨尔县| 宜黄县| 稻城县| 突泉县| 巴中市| 淮南市| 洪湖市| 邳州市| 新闻| 白山市| 和静县| 防城港市| 南陵县| 托克逊县| 长宁县| 鹤山市| 洞口县| 双城市| 七台河市| 凉城县| 乐昌市| 兴海县| SHOW| 长丰县| 刚察县| 嘉鱼县| 柳江县| 庆城县| 正安县| 中阳县| 象山县| 巧家县| 虹口区| 收藏| 突泉县| 金寨县| 阜新市| 鄯善县| 扎囊县|