【问题标题】:RESTful servlet URLs - servlet-mapping in web.xmlRESTful servlet URL - web.xml 中的 servlet 映射
【发布时间】:2012-04-17 12:07:29
【问题描述】:

我觉得这是一个常见问题,但我研究过的任何东西都没有奏效......

在我的 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 ()。我不确定它是否能通过 Spring 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));
}

变量名不匹配让我...我把它留在这里作为对所有人的警告...匹配你的变量名!

【问题讨论】:

  • 你能发布你的控制器代码吗?我的猜测是你只映射了/people 而不是/people/{id}
  • @matsev 我为您发布了代码。感谢您查看。
  • web.xml 中的映射是可以的。您可以在此处粘贴 /rest/people/1 的控制器类方法()的代码吗?也许我可以帮忙。

标签: java rest servlets spring-mvc url-pattern


【解决方案1】:

尝试在{id} 之前添加/

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

没有它,id 将直接附加到人员 url,例如 /rest/people1 而不是 /rest/people/1

【讨论】:

    猜你喜欢
    • 2015-03-01
    • 2013-01-20
    • 2010-10-04
    • 2016-07-05
    • 2013-03-01
    • 2012-07-23
    • 2012-01-02
    相关资源
    最近更新 更多