Spring MVC 提供了以下这些请求映射注解:
请求映射注解 | 说明 |
---|---|
@RequestMapping | 通用的请求处理 |
@GetMapping | 处理 HTTP GET 请求 |
@PostMapping | 处理 HTTP POST 请求 |
@PutMapping | 处理 HTTP PUT 请求 |
@DeleteMapping | 处理 HTTP DELETE 请求 |
@PatchMapping | 处理 HTTP PATCH 请求 |
除了 @RequestMapping ,其它类型的注解本质上是 @RequestMapping 的简写形式。比如 @GetMapping 其实可以写为:
@RequestMapping( method = RequestMethod.GET)
建议在类级别上只使用 @RequestMapping ,用于指定基本路径。而在每个处理器方法上,使用更具体的请求映射注解,比如 @GetMapping。
以下是使用 Spring Web 注解定义控制器的典型示例:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Arrays;
import java.util.List;
/**
* 商品控制器
* <p/>
*
* @author Deniro Lee
*/
@Controller
@RequestMapping("/product")
public class ProductController {
@GetMapping("/show")
public String show(Model model) {
List<Product> products = Arrays.asList(
new Product("1", "xx 微波炉", 2299),
new Product("2", "xx 电视", 1789),
new Product("3", "xx 笔记本电脑", 5399)
);
model.addAttribute("products", products);
return "product";
}
}
Model 对象的作用是在控制器和视图之间传递数据。放到 Model 对象中的数据会复制到 ServletResponse 属性中,这样在视图中就能找到它们,然后依据业务逻辑渲染出来。
这里的 product 就是视图名,如果配置了 thymeleaf 模板框架,那么 Spring 就会在 resources/templates/ 下找到名为 product.html 模板页,进行后续渲染: