springMVC第一天

 

 来看几个例子 , 秒懂 , 很简单

//http://localhost/param5?username=zhangsan&age=18
    @GetMapping("/param5")
    public String param5(@RequestParam Map<String,String> map){
        map.forEach((k,v)->{
            System.out.println(k+"==>"+v);
        });
        return "/index.jsp";
    }


    //http://localhost/param4?hobby=zq&hobby=pq&hobby=tq
    @GetMapping("/param4")
    public String param4(@RequestParam List<String> hobby){
        for (String s : hobby) {
            System.out.println(s);
        }
        return "/index.jsp";
    }


    //http://localhost/param3?hobby=zq&hobby=pq&hobby=tq
    @GetMapping("/param3")
    public String param3(String[] hobby){
        for (String s : hobby) {
            System.out.println(s);
        }
        return "/index.jsp";
    }


    //http://localhost/param2?username=zhangsan&age=18
    @GetMapping("/param2")
    public String param2(@RequestParam(value="username",required = false,defaultValue = "haohao") String name, Integer age){
        System.out.println(name+"===="+age);
        return "/index.jsp";
    }

    //http://localhost/param1?username=zhangsan&age=18
    @RequestMapping("/param1")
    public String param1(String username,int age){
        System.out.println(username+"===="+age);
        return "/index.jsp";
    }

来看第二种方式

 

 用一个user类封装信息 , 很方便 ,(SpringMVC容器已经帮我们把User对象创建了)

    //http://localhost/param6?username=zhangsan&age=18&hobbies=zq&hobbies=pq&birthday=2018/11/11&address.city=tj&address.area=bh
    @GetMapping("/param6")
    public String param6(User user){
        System.out.println(user);
        return "/index.jsp";
    }

3.传递json数据

第一步、导入json坐标

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>

第二步 ,在springmvc.xml配置文件导入配置

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
    </bean>

 

第三步 .配置映射路径及方法资源

  //http://localhost/param9
    @PostMapping("/param9")
    public String param9(@RequestBody User user) throws JsonProcessingException {
        System.out.println(user);
        return "/index.jsp";
    }
@RequestBody 与 @RequestParam
区别 :

@RequestParam用于接收url地址传参,表单传参[application/x-www-form-urlencoded]

@RequestBody用于接收json数据[application/json]

应用
后期开发中,发送json格式数据为主,@RequestBody应用较广

如果发送非json格式,选用@RequestParam格式接收请求参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值