今天想到一个问题
背景 使用rest风格做java web 项目
一般的url http://www.blog.com/info/{type}/{userId} 后台约定风格
http://www.blog.com/info/01/1 正常的url请求
正常后台函数
@RequestMapping(value="{type}",value="{userId}" ,method=RequestMethod.GET)
public ModelAndView toItem(@PathVariable("type")String type,@PathVariable("userId")Long userId){
.......
}
如果这个时候我的type参数可以为空,也可以传入一个值时,后台接受参数应该怎么写?
推测:1.需要在写一个后台对应的函数,接受type为空,即没有type参数url http://www.blog.com/info/{userId} 的后台函数,根据不同的请求url 访问不同的函数。(代码 重复性太高)
2.前台在传入参数是 如果type没有参数,可以后后台 约定传入一个值表示此参数无效(例如 type不可能为-1,如果为空时 就传入-1),后台判断处理。
3.希望推荐一种简单的方式,例如说加一个注解就可以解决或者其他简单方式。
http://www.blog.com/info/{type}/{userId}这种type真的可空吗
http://www.blog.com/info?type=01&userId=1 这种可空吧。
写错了
@RequestMapping("/info/{type}/{userId}")
public String getTypeUserId(@PathParam("type")String type,@PathParam("userId") String userId){
//your code
}
@RequestMapping("/info/{userId}")
public String getUserIdWithoutType(@PathParam("userId") String userId){
return getTypeUserId(null,userId);
}
可以声明两个ReqeustMapping,一个带Type,一个不带,不带Type的方法收到后直接调用带Type的。如
@RequestMapping("/info/{type}/{userId}")
public String getTypeUserId(@PathParam("type")String type,@PathParam("userId") String userId){
//your code
}
@RequestMapping("/info/{type}/{userId}")
public String getUserIdWithoutType(@PathParam("userId") String userId){
return getTypeUserId(null,userId);
}
直接用POST不就可以了吗?参数不放到url里面 到时候你想空就空 代码里面判断就好了