如何解决使用Spring可以使路径变量可选吗?
你不能具有可选的路径变量,但是可以有两个调用相同服务代码的控制器方法:
@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 4.1和Java 8,你可以使用java.util.Optional
它支持@RequestParam
,@PathVariable
,@RequestHeader
和@MatrixVariableSpring MVC
中-
@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
@PathVariable Optional<String> type,
@RequestParam("track") String track) {
if (type.isPresent()) {
//type.get() will return type value
//corresponds to path "/json/{type}"
} else {
//corresponds to path "/json"
}
}
解决方法
在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",@RequestParam(value = "type",required = false) String type,@RequestParam("track") String track) {
return new TestBean();
}
然后/json?type=abc&track=aa或/json?track=rr将工作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。