来看几个例子 , 秒懂 , 很简单
//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格式接收请求参数