簡體   English   中英

帶有多個斜線的Spring路徑參數

[英]Spring path params with multiple slash

我有一個Spring Boot應用程序,其中有一個API,它將其他URL用作路徑參數。 例如:

host:port/{eid}是我的基本路徑,在此之后,我可以使用如下網址

host:port/{eid}/abc
host:port/{eid}/abc/pqr/
host:port/{eid}/abc/pqr/b=2
host:port/{eid}/abc/pqr/xyz
host:port/{eid}/abc/pqr/xyz?a=1

...等等...

我想定義一個控制器,我可以將其映射到上述所有URL,並且應該可以像

@RequestMapping(value = "/{eid}/{urlParts}", method = RequestMethod.GET)
public ResponseEntity<Object> share(
        @PathVariable String eid, 
        @PathVariable String urlParts) {
 ...... 
}

我嘗試使用@PathVariable Map<String, String> path ,也使用@RequestMapping(value = "/{eid}/{urlParts:.+}"

但無法獲得預期的結果。

有什么解決方案可以在路徑參數中接收路徑斜杠(/)。

注意 :我無法對 URL中的斜杠(/)進行URL編碼。 這不是我的選擇。

如果您使用jsp或其他工具,為什么不嘗試使用@RequestParam獲取URL。

@PathVariable意味着應從調用的URL的路徑中提取帶注釋的方法參數。 @RequestParam意味着必須從請求參數中提取帶注釋的方法參數。 這些注釋都不會導致將注釋的參數放入請求,會話或應用程序范圍。

因此您也可以使用地圖...

$ {用戶名}的意思是“在響應中寫入用戶名屬性的值(在頁面,請求,會話,應用程序范圍中找到)”。 由於您在這些范圍中均未包含任何用戶名屬性,因此不會編寫任何內容。

如果該方法返回了ModelAndView對象,並且該模型包含用戶名屬性和Studentid屬性,則該代碼將起作用。

您可以參考以下代碼和鏈接:

第一個URL:localhost:8080 / projectName / test?firstname = john

第二個URL:localhost:8080 / projectName / test?firstname = john&secondname = roy

    @Controller
    @RequestMapping("/test")
    public class TestController {




    @RequestMapping(value = { "/test/{firstname}/test" }, method = { RequestMethod.GET })
public String someMethod(@PathVariable("firstname") String firstname){
    return someMethod(firstValue )

}

    @RequestMapping(value = { "/test/{firstname}/{otherString}/test" }, method = { RequestMethod.GET })
public String someOtherMethod(@PathVariable("firstname") String firstname, @PathVariable("secondname") String secondValue) {
    return someMethod(firstValue + "/" + secondValue)

 }
}

因此,我不確定是否有直接的Spring實施方式可以執行此操作,但是,您可能會遇到一些麻煩。

  • @RequestParam-返回URL參數的映射(在?
  • @PathVariable-返回eid
  • HttpServletRequest-使用該請求返回URI並剝離host:port / {eid}及其后的任何內容? ,然后使用Arrays.asList(str.split(“ /”)); (請記住,這是使用new ArrayList<Sting>(Arrays.asList(str.split("/")))的數組包裝new ArrayList<Sting>(Arrays.asList(str.split("/")))

     @RequestMapping(value = "/{eid}", method = RequestMethod.GET) public ResponseEntity<Object> share( @PathVariable String eid, @RequestParam Map<String,String> allRequestParams, HttpServletRequest request) { ...... } 

我知道查詢太舊了,但仍然有用,這個答案可以幫助其他人。 您可以使用request屬性獲取完整的url部分,如下所示。

@RequestMapping(value = "/{eid}/**", method = RequestMethod.GET)
public ResponseEntity<Object> share(@PathVariable String eid, HttpServletRequest request) {

    Object uriObject = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    if (null != uriObject) {
        String urlParts = uriObject.toString().replaceFirst("^/" eid + "/", "");
    }
    ....
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM