package per.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import per.lcm.pojo.User;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
@RestController
public class RequestController {
// 使用HttpServletRequest接收参数
@RequestMapping(value = "/simpleParam0")
public String simpleParam0(HttpServletRequest request) {
String name = request.getParameter("name");
String ageStr = request.getParameter("age");
int age = Integer.parseInt(ageStr);
System.out.println("name = " + name + ", age = " + age);
return "OK";
}
// 使用@RequestParam, 请求参数名与形参名相同时,可不加@RequestParam
@RequestMapping(value = "/simpleParam1")
public String simpleParam1(String name, @RequestParam("age66") int age){
System.out.println(name + ":" + age);
return name + ":" + age;
}
// 简单实体参数
@RequestMapping(value = "/simplePojo")
public String simplePojo( User user){
System.out.println(user);
return user.getName() + ":" + user.getAge();
}
// 复杂实体参数(实体嵌套)
@RequestMapping(value = "/complexPojo")
public String complexPojo(User user){
System.out.println(user);
return "OK";
}
// 数组参数:参数名与数组名相同
@RequestMapping(value = "/arrayParam")
public String arrayParam(String[] hobby){
System.out.println(Arrays.toString(hobby));
return "OK";
}
// List参数:参数名与数组名相同且使用@RequestParam(因为默认使用数组封装)
@RequestMapping(value = "/listParam")
public String listParam(@RequestParam List<String> hobby){
System.out.println(hobby);
return "OK";
}
// 日期参数:@DateTimeFormat 指定接收日期参数的格式
@RequestMapping(value = "/dateParam")
public String dateParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime){
System.out.println(updateTime);
return "OK";
}
// json参数
@RequestMapping(value = "/jsonParam")
public String jsonParam(@RequestBody User user){
System.out.println(user);
return "OK";
}
// path参数
@RequestMapping(value = "/pathParam/{id66}/{job}")
public String pathParam(@RequestBody User user, @PathVariable("id66") int id, @PathVariable String job){
System.out.println(user);
System.out.println("id:" + id);
System.out.println("job:" + job);
return "OK";
}
}
涉及到的实体类:
public class User {
private String name;
private Integer age;
private Address address;
}
public class Address {
private String province;
private String city;
}