2012-04-03 91 views
2

我覺得這是一個常見的問題,但沒有我研究還沒有工作...REST風格的servlet的URL - 在web.xml中的servlet映射

在我的web.xml我有一個映射爲所有REST電話 -

<servlet-mapping> 
    <servlet-name>springmvc</servlet-name> 
    <url-pattern>/rest/*</url-pattern> 
    </servlet-mapping> 

這種運作良好,如果URL -

GET /rest/people 

失敗如果是

GET /rest/people/1 

我收到一個400 Bad Request錯誤,說The request sent by the client was syntactically incorrect()。我不知道它甚至去到春節servlet來獲取路由...

我怎樣才能通配符任何/rest啓動,以便它可以被適當處理?

換句話說,我想對所有以下是有效的 -

GET /rest/people 
GET /rest/people/1 
GET /rest/people/1/phones 
GET /rest/people/1/phones/23 

編輯 - 控制器代碼的要求

@Controller 
@RequestMapping("/people") 
public class PeopleController { 

    @RequestMapping(method=RequestMethod.GET) 
    public @ResponseBody String getPeople() { 
     return GsonFactory.getInstance().toJson(LookupDao.getInstance().getPeople()); 
    } 

    @RequestMapping(value="{id}", method=RequestMethod.GET) 
    public @ResponseBody String getPerson(@PathVariable String id) { 
     return GsonFactory.getInstance().toJson(LookupDao.getInstance().getPerson(id)); 
    } 
} 

回答

@matsev如果我在那裏有/這似乎沒有關係。

雖然我將公共視圖的變量名換位,但我改變了一些東西以使其工作。

原始

@RequestMapping(value="{id}", method=RequestMethod.GET) 
public @ResponseBody String getPerson(@PathVariable String userId) { 
    return GsonFactory.getInstance().toJson(LookupDao.getInstance().getPerson(userId)); 
} 

我張貼

@RequestMapping(value="{id}", method=RequestMethod.GET) 
public @ResponseBody String getPerson(@PathVariable String id) { 
    return GsonFactory.getInstance().toJson(LookupDao.getInstance().getPerson(id)); 
} 

的變量的名稱不匹配確實我......我離開這個位置,以警示所有比賽...你的變量名!

+0

你可以發佈你的控制器代碼嗎?我的猜測是你只映射了'/ people'而不是'/ people/{id}'。 – matsev 2012-04-03 19:38:02

+0

@matsev我發佈了你的代碼。感謝檢查出來。在web.xml中映射 – 2012-04-03 19:41:45

+0

是可以的。你可以在這裏粘貼控制器類方法的代碼()for/rest/people/1嗎?可能是我可以幫忙。 – shashankaholic 2012-04-03 19:49:28

回答

4

嘗試添加/{id}

@RequestMapping(value="/{id}", method=RequestMethod.GET) 

沒有它,ID將直接附加到人URL,e.g /rest/people1而不是/rest/people/1