欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC页面向Controller传参

程序员文章站 2022-03-20 12:29:20
关于SpringMVC页面向Controller传参的问题,看了网上不少帖子,大多总结为以下几类: 1、直接把页面表单中相关元素的name属性对应的值作为Controller方法中的形参。 这个应该是最直接的,我看的那本书从百度的编辑器中取内容content时就直接用的这个方法: 2、通过@Requ ......

关于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("参数")绑定到后面跟的形参,后台在处理时根据实际需要可以改变参数名称。