bellus- 2016-12-16 02:05 采纳率: 0%
浏览 5386
已结题

java web项目中使用rest风格的url参数可有可无时表示方法?

            今天想到一个问题
            背景   使用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.希望推荐一种简单的方式,例如说加一个注解就可以解决或者其他简单方式。
  • 写回答

4条回答 默认 最新

  • 邓志国77 2016-12-16 02:37
    关注

    写错了

     @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);
    }
    
    评论
  • 邓志国77 2016-12-16 02:39
    关注

    可以声明两个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);
    }
    
    评论
  • 来啊快活啊 2016-12-16 04:08
    关注

    直接用POST不就可以了吗?参数不放到url里面 到时候你想空就空 代码里面判断就好了

    评论

报告相同问题?

悬赏问题

  • ¥15 咨询bilbil上这个视频音字同步的效果用什么软件可实现?
  • ¥15 西门子plc6ES7217-1AG40-0XB0怎么rs485通讯呀!
  • ¥15 matlab有svec这个函数吗?
  • ¥15 无法调用VideoWriter_fourcc
  • ¥15 VB6.0无法加载网页验证码图片到picturebox中,求解。
  • ¥15 C#和GDAL对栅格处理
  • ¥15 我现在有一些关于提升机故障的专有文本数据,量也不多,我在label studio上进行了关系和实体的标注,完成了知识图谱的构造,那么我使用生成式模型的话,我能做哪些工作来写我的论文?
  • ¥15 电脑连不上无线网络如下诊断反馈应该如何操作
  • ¥15 telegram api 使用forward_messages方法转发消息时,目标群组里面会出现此消息来源,如何隐藏?
  • ¥15 关于#tensorflow#的问题:有没有什么方法可以让机器自己学会像素风格的图片