2017-01-12 83 views
0

我想在我的參數傳遞給我的web服務的格式爲:彈簧組默認PathVariable

http://.../greetings/neil/1

不是

http://.../greetings?name=neil&id=1

所以我改變了我的代碼(注意,我只在代碼中包含第一個參數):

@RequestMapping("/greeting") 
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { 
    return new Greeting(counter.incrementAndGet(), 
         String.format(template, name)); 
} 

到:

@RequestMapping 
public Greeting greeting(@PathVariable String name) { 
    return new Greeting(counter.incrementAndGet(), 
         String.format(template, name)); 
} 

它的工作原理,但我不知道如何添加默認值@PathVariable使得例如:

http://.../greetings/

http://.../greetings/neil/

會工作,因爲它用查詢參數。

我該怎麼做?我想也許它會傳遞null,但它只是產生一個頁面錯誤。

我想答案可能是添加多個重載,但這聽起來有點亂。

謝謝。

謝謝。

+2

[Spring MVC中的可能重複:如何指示的路徑變量是否需要與否?](http://stackoverflow.com/questions/17821731/spring-mvc-how-to-indicate-whether-a-path-variable-is-required-or-not) – Arpit

回答

2

以下方法如何?我正在使用java.util.Optional類,它充當可以爲null或not-null的對象的包裝器。

@RequestMapping 
public Greeting greeting(@PathVariable Optional<String> name) { 
    String newName = ""; 
    if (name.isPresent()) { 
     newName = name.get() //returns the id 
    } 
    return new Greeting(counter.incrementAndGet(), 
         String.format(template, newName)); 
} 

或者,你可以定義兩個單獨的請求映射處理程序:

@RequestMapping("/greeting") 
public Greeting defaultGreeting() 

@RequestMapping("/greeting/{name}") 
public Greeting withNameGreeting(@PathVariable String name) 
+0

第二種方法我已經這樣做了,但想要一些像你的冷杉t方法。但是,如果沒有提供任何內容,即/問候語,我無法使其工作。我是否需要向班級添加任何內容?我唯一可以做的就是添加:@RequestMapping(「/ greeting/{name}」) –

+0

你是說當你使用@RequestMapping(「/ greeting/{name}」)然後調用URL /問候語,它不起作用? Spring拋出什麼異常? – VHS