1、簡單引數的接受
package cn.ssdt.tim; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class RequestController { // 方式一 原始的請求引數 @RequestMapping("/simpleParam") public String simpleParam(HttpServletRequest request) { String name = request.getParameter("name"); String ageStr = request.getParameter("age"); int age = Integer.parseInt(ageStr); System.out.println(name); System.out.print(age); return "ok"; } // 方式二 springboot 請求引數 @RequestMapping("/simpleParam2") public String simpleParam2(String name,Integer age) { System.out.println(name + ":"+age); return "ok"; } // post 請求 @RequestMapping("/simpleParam3") public String postSimpleParam(String name,Integer age) { System.out.println(name + ":"+age); return "ok"; } // @RequestParam 中的required屬性預設true 代表該引數必須傳遞。若需要可選,可設定為false @RequestMapping("/simpleParam4") public String postSimpleParam2(@RequestParam(name="name",required=false)String username,Integer age) { System.out.println(username + ":"+age); return "ok"; } }
2、實體請求引數
package cn.ssdt.tim.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import cn.ssdt.tim.pojo.User; @RestController public class RequestController2 { @RequestMapping("/simplePojo") public String simplePojo(User user) { System.out.println(user); return "ok"; } }
package cn.ssdt.tim.pojo; public class User { private String name; private Integer age; private Address address; public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", address=" + address + "]"; } }
package cn.ssdt.tim.pojo; public class Address { private String province; private String city; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Address [province=" + province + ", city=" + city + "]"; } }