接收params参数
通过方法的形参来接收request的同名参数
@RequestMapping("/commonParam")
@ResponseBody
public String commonParam(String name,Integer age,String address){
System.out.println("name:"+name);
System.out.println("age:"+age);
System.out.println("address:"+address);
return "{'user':'save'}";
}
@RequestMapping("pojoParam")
@ResponseBody
public String pojoParam(User user){
return "{'user':"+user+"}";
}
@RequestMapping("listParam")
@ResponseBody
public String listParam(@RequestParam("likes") List<String> list){
return list.toString();
}
如果中文參數出现亂碼的問題,添加一個編碼過濾器
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
return new Filter[]{filter};
}
请求参数如果与形参不同名,使用@RequestParam()匹配
@RequestMapping("commonParamDifferentName")
@ResponseBody
public String commonParamDifferentName(@RequestParam("name") String userName, Integer age){
System.out.println("userName:"+userName);
System.out.println("age:"+age);
return "{'user':'save'}";
}
接收json类型的参数
1.在Maven中导入jackson-databind坐标
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
2.在配置文件中开启@EnableWebMvc
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan({"com.lipeng.controller"})
@EnableWebMvc
public class SpringMvcConfig {
}
3.形参添加@RequestBody注解
@RequestMapping("listParamForJson")
@ResponseBody
public String listParamForJson(@RequestBody List<String> list){
return list.toString();
}
@RequestMapping("pojoParamForJson")
@ResponseBody
public String pojoParamForJson(@RequestBody User user){
return user.toString();
}
@RequestMapping("listPojoParamForJson")
@ResponseBody
public String listPojoParamForJson(@RequestBody List<User> users){
return users.toString();
}