zoukankan      html  css  js  c++  java
  • @params、@PathVariabl和@RequestParam用法与区别

    【1】params

    params: 指定request中必须包含某些参数值是,才让该方法处理。

        @RequestMapping(value = "testParamsAndHeaders", params = { "username","age!=10" })
        public String testParamsAndHeaders() {
            System.out.println("testParamsAndHeaders");
            return SUCCESS;
        }

    params 只是判断url 或者 form data 中的参数是否复合params的定义,并不会直接绑定数据到方法的参数中!


    【2】@PathVariabl

    • 绑定路径中的占位符参数到方法参数变量中;

    • 只能绑定路径中的占位符参数,且路径中必须有参数。

    无论是 GET 或者POST 只要 URL中有参数即可!

    如:

    • GET
    Request URL:http://localhost:8080/SpringMVC-1/springmvc/testPathVariable/1
    • POST
        <form action="springmvc/testPathVariable/1" method="POST">
            <input type="text" name="username" value=""/>
            <input type="text" name="age" value=""/>
            <input type="text" name="sex" value=""/>
            <input type="submit" value="submit"/>
        </form>

    【注意:】如果URL中无参数,将会出错;如果URL有参数,但是没有使用@PathVariabl该注解,那么URL的参数不会默认与方法参数绑定!方法里的参数会默认绑定表单里面对应的参数!


    • 后台code

    如果参数名与占位符一致,则可直接使用@PathVariable;

    如果不一致,则在@PathVariable( )括号内绑定占位符。

        @RequestMapping("/testPathVariable/{id}")
        public String testPathVariable(@PathVariable("id") Integer id2) {
            System.out.println("testPathVariable: " + id2);
            return SUCCESS;
        }

    【3】@RequestParam

    • value:参数key,可以不写;

    • required:默认值为true,可以不写;

    • 获取URL或者 form data 中的参数

    • GET

    <a href="springmvc/testRequestParam?username=atguigu&age=11&sex=boy">
    • POST
        <form action="springmvc/testRequestParam" method="POST">
            <input type="text" name="username" value=""/>
            <input type="text" name="age" value=""/>
            <input type="text" name="sex" value=""/>
            <input type="submit" value="submit"/>
        </form>

    注意 :

    GET中的参数形式为:username=atguigu&age=11&sex=boy

    POST中的参数形式为:以键值对形式保存在form data

  • 相关阅读:
    JavaScript你所不知道的困惑(3)
    Android的代码都得自己一个个敲一遍吗?
    现代化农业在美国的兴起与发展
    高内聚与低耦合实现小记
    iOS 载入图片选择imageNamed 方法还是 imageWithContentsOfFile?
    swift笔记——环境搭建及Hello,Swift!
    HDU 4832(DP+计数问题)
    [TJOI2019]甲苯先生的线段树
    2019-8-31-C#-如何写-DEBUG-输出
    2019-8-31-C#-如何写-DEBUG-输出
  • 原文地址:https://www.cnblogs.com/austinspark-jessylu/p/7840586.html
Copyright © 2011-2022 走看看