【Java】@PathVariable與@RequestParam 影響後臺引數型別與前臺傳參的形式
阿新 • • 發佈:2019-01-01
前言
小編最近在維護專案的過程中,遇到了swagger中不同環境下的同一方法執行效果不同。一、問題背景
自己在寫SSM框架中的controller層寫方法時,將兩個注入@PathVariable與@RequestParam的概念沒有理解清楚,導致Tomcat攔截了錯誤的語法。本地執行成功而在Nginx伺服器部署後的環境被攔截。(自己聽了公司技術老總的分析後,大體的理解是這樣的,可能會有一些偏差。)
二、兩種註解在後端如何正確使用
1.第一種情況引數都使用@RequestParam注入,那麼地址的拼寫是不需要加引數的。
@RequestMapping(value = {"/findDictionarybyTypeId"} , method = RequestMethod.GET)
@ResponseBody
public ItooResult findDictionarybyTypeId(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false, defaultValue = "") String typeId, @RequestParam(required = false, defaultValue = "") String dictionaryInfo)
在swagger中的展現形式:
2.另一種情況引數使用@PathVariable注入,那麼地址的拼寫是需要加引數值的。
@RequestMapping(value = {"/exportToExcel/{typeId}"}, method = RequestMethod.GET)
@ResponseBody
public ItooResult exportToExcel(HttpServletRequest request, HttpServletResponse response, @PathVariable String typeId, @RequestParam(required = false , defaultValue = "") String dictionaryInfo)
在swagger中的展現形式:
三、兩種註解影響前端URL拼寫
1.使用@RequestParam注入的地址拼寫:引數需要寫引數名:‘?typeId=’ + this.dictionnaryId
url = 'http://192.168.22.52:8080/single-web/dictionary/findDictionarybyTypeId' + '?typeId=' + this.dictionnaryId + '&dictionaryInfo=' + this.info;
2.使用@PathVariable注入的地址拼寫:引數直接傳值:this.dictionnaryId
const url = 'http://192.168.22.52:8080/single-web/dictionary/exportToExcel/' + this.dictionnaryId + '?dictionaryInfo=' + this.info;