1. 首页
  2. 软件开发
  3. Spring MVC——关于RequestMapping注解的用法,你全都知道吗!!!

Spring MVC——关于RequestMapping注解的用法,你全都知道吗!!!

  • 发布于 2024-08-17
  • 0 次阅读

@RequestMapping注解在Spring MVC中用于映射请求URL到处理器方法。它可以用在类级别和方法级别,用于定义处理请求的路径、请求方法、请求参数等信息。

  1. 在类级别使用@RequestMapping
    指定整个Controller处理的基本URL路径。
@Controller
@RequestMapping("/products")
public class ProductController {
   
    
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String getProductById(@PathVariable("id") Long id, Model model) {
   
        // 处理获取商品详情的逻辑
        return "productDetails";
    }
}
  1. 指定请求方法
    限定处理器方法对应的请求方法。
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveProduct(@ModelAttribute Product product) {
   
    // 处理保存商品的逻辑
    return "redirect:/products";
}
  1. 接收请求参数
    绑定请求参数到方法参数。
@RequestMapping(value = "/search", method = RequestMethod.GET)
public String searchProduct(@RequestParam("keyword") String keyword, Model model) {
   
    // 处理搜索商品的逻辑
    return "searchResults";
}
  1. 使用多个路径映射
    可以指定多个路径映射到同一个处理器方法。
@RequestMapping(value = {
   "/info", "/details"}, method = RequestMethod.GET)
public String getProductInfo(Model model) {
   
    // 处理获取商品信息的逻辑
    return "productInfo";
}
  1. 使用通配符
    支持Ant风格的路径通配符。
@RequestMapping(value = "/products/*/details", method = RequestMethod.GET)
public String getProductDetails(Model model) {
   
    // 处理获取商品详细信息的逻辑
    return "productDetails";
}
  1. 使用正则表达式
    支持正则表达式的路径匹配。
@RequestMapping(value = "/products/{category:[a-z]+}/{id:\\d+}", method = RequestMethod.GET)
public String getProductByCategoryAndId(@PathVariable String category, @PathVariable Long id, Model model) {
   
    // 处理根据分类和ID获取商品的逻辑
    return "productDetails";
}

原文链接: https://blog.csdn.net/2401_82884096/article/details/137997194