目录
前言
什么是查询字符串和查询参数?
https://example.com/products?category=electronics&price=100
Spring MVC中的查询参数
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class ProductController {
@RequestMapping("/products")
public String getProducts(
@RequestParam String category,
@RequestParam int price) {
// 处理查询参数
// ...
return "products";
}
}
处理可选参数
@RequestMapping("/products")
public String getProducts(
@RequestParam String category,
@RequestParam(required = false) Integer price) {
// 处理查询参数
// ...
return "products";
}
处理多个值
@RequestMapping("/products")
public String getProducts(
@RequestParam String category,
@RequestParam List<String> tags) {
// 处理多个值的查询参数
// ...
return "products";
}
处理查询参数的默认值
@RequestMapping("/products")
public String getProducts(
@RequestParam(defaultValue = "all") String category,
@RequestParam(defaultValue = "0") int price) {
// 处理查询参数
// ...
return "products";
}
处理查询字符串
@RequestMapping("/products")
public String getProducts(@RequestParam Map<String, String> params) {
// 处理查询参数的Map
// ...
return "products";
}
示例:创建一个RESTful服务
public class Product {
private String name;
private String category;
private double price;
// 省略构造函数和getter/setter
}
@Controller
public class ProductController {
private List<Product> products = new ArrayList<>();
public ProductController() {
// 初始化产品列表
products.add(new Product("Laptop", "Electronics", 799.99));
products.add(new Product("Headphones", "Electronics", 149.99));
products.add(new Product("T-shirt", "Clothing", 19.99));
}
@RequestMapping("/products")
public ResponseEntity<List<Product>> getProducts(
@RequestParam(required = false) String category,
@RequestParam(defaultValue = "0") double maxPrice) {
List<Product> result = new ArrayList<>();
for (Product product : products) {
if ((category == null || product.getCategory().equals(category)) &&
product.getPrice() <= maxPrice) {
result.add(product);
}
}
return new ResponseEntity<>(result, HttpStatus.OK);
}
}