关于SpringMVC页面向Controller传参的问题,看了网上不少帖子,大多总结为以下几类:

1、直接把页面表单中相关元素的name属性对应的值作为Controller方法中的形参。

  这个应该是最直接的,我看的那本书从百度的编辑器中取内容content时就直接用的这个方法:

<!--页面-->
<
form action="<%=basePath%>saveUeditorContent" method="post"> <!-- 加载编辑器的容器 --> <div style="padding: 0px;margin: 0px;width: 100%;height: 100%;" > <script id="container" name="content" type="text/plain"> </script> <!--why dose this use script tag here???--> </div> <input name="test_input" value="hengha"> <button type="submit"> 保存</button> </form>

 

    //Controller
    @RequestMapping(value="/saveUeditorContent")
    public ModelAndView saveUeditor(String content, String test_input){
        ModelAndView mav = new ModelAndView("myJSP/test03");
        //addObject方法设置了要传递给视图的对象
        mav.addObject("content", content);
        mav.addObject("input_content", test_input);
        //返回ModelAndView对象会跳转至对应的视图文件。也将设置的参数同时传递至视图
        return mav;
    }

 

2、通过@RequestParam把页面表单中相关元素的name属性对应的值绑定Controller方法中的形参。

用于URL带?场景,/saveUeditorContent?content=123&input_content=456,参数可以设置是否必须required,默认值defaultvalue

    @RequestMapping(value="/saveUeditorContent")
    public ModelAndView saveUeditor(@RequestParam(value="content",required=true,defaultValue="123") String content, @RequestParam("test_input") String input_content){
        ModelAndView mav = new ModelAndView("myJSP/test03");
        mav.addObject("content", content);
        mav.addObject("input_content", input_content);
        return mav;
    }

 

3、通过@PathVariable获取@RequestMapping中URL路径带入的{变量}绑定Controller方法中的形参。

用于URL直接传参场景,/saveUeditorContent/123/456

    @RequestMapping(value="/saveUeditorContent/{content}/{test_input}")
    public ModelAndView saveUeditor(@PathVariable("content") String content, @PathVariable("test_input") String input_content){
        ModelAndView mav = new ModelAndView("myJSP/test03");
        mav.addObject("content", content);
        mav.addObject("input_content", input_content);
        return mav;
    }

 

4、创建属性名对应页面表单中相关元素带setter和getter方法的POJO对象作为Controller方法中的形参。

    //太晚了不是特别熟不整了

5、把HttpServletRequest对象作为Controller方法中的形参。

    @RequestMapping(value="/saveUeditorContent")
    public ModelAndView saveUeditor(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("myJSP/test03");
        mav.addObject("content", request.getParameter("content"));
        mav.addObject("input_content", request.getParameter("test_input"));
        return mav;
    }

 

约束说明:

a) 1中的形参,2中的RequestParam("参数"),3中的URL中的{参数}以及PathVariable("参数"),4中的POJO对象属性,5中的request.getParameter("参数")均需要和前台页面中相关元素name属性对应的值匹配。

b) 2中的RequestParam("参数"),3中的PathVariable("参数")绑定到后面跟的形参,后台在处理时根据实际需要可以改变参数名称。

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程