使用Spring可以使路径变量可选吗?

Spring 3.0中,我可以有一个可选的path变量吗?

例如

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

public @ResponseBody TestBean testAjax(

HttpServletRequest req,

@PathVariable String type,

@RequestParam("track") String track) {

return new TestBean();

}

在这里我想/json/abc还是/json要调用相同的方法。

一种明显的解决方法是声明type为请求参数:

@RequestMapping(value = "/json", method = RequestMethod.GET)

public @ResponseBody TestBean testAjax(

HttpServletRequest req,

@RequestParam(value = "type", required = false) String type,

@RequestParam("track") String track) {

return new TestBean();

}

然后/json?type=abc&track=aa或/json?track=rr将工作

回答:

你不能具有可选的路径变量,但是可以有两个调用相同服务代码的控制器方法:

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

public @ResponseBody TestBean typedTestBean(

HttpServletRequest req,

@PathVariable String type,

@RequestParam("track") String track) {

return getTestBean(type);

}

@RequestMapping(value = "/json", method = RequestMethod.GET)

public @ResponseBody TestBean testBean(

HttpServletRequest req,

@RequestParam("track") String track) {

return getTestBean();

}

以上是 使用Spring可以使路径变量可选吗? 的全部内容, 来源链接: utcz.com/qa/410283.html

回到顶部