SpringMVC常用的注解

Spring MVC 提供了丰富的注解,这些注解可以简化开发过程,提高开发效率,使代码结构更加清晰。以下是 Spring MVC 中一些常用注解的详细介绍:

1. 控制器相关注解

1.1 @Controller
  • 作用:用于标记一个类为控制器类,告知 Spring 该类是处理 Web 请求的控制器。它是一个特殊的组件,Spring 会自动扫描带有该注解的类,并将其纳入 Spring 容器进行管理。

  • 示例

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    public class HelloController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
    return "Hello, Spring MVC!";
    }
    }

在上述示例中,HelloController 类被 @Controller 注解标记,成为一个控制器类,其中的 hello 方法可以处理 /hello 请求。

1.2 @RestController
  • 作用 :这是 @Controller@ResponseBody 的组合注解。使用 @RestController 标记的类,其所有方法的返回值都会被直接作为响应体返回,而不会经过视图解析器解析为视图。通常用于开发 RESTful 风格的 Web 服务。

  • 示例

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class UserController {
    @GetMapping("/users/{id}")
    public String getUser(@PathVariable("id") int id) {
    return "User with id: " + id;
    }
    }

在这个例子中,UserController 类使用 @RestController 注解,getUser 方法的返回值会直接作为 HTTP 响应返回给客户端。

2. 请求映射注解

2.1 @RequestMapping
  • 作用:用于将 HTTP 请求映射到控制器的方法上。可以指定请求的 URL、请求方法(如 GET、POST 等)、请求参数、请求头、媒体类型等条件。

  • 示例

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    public class ProductController {
    @RequestMapping(value = "/products", method = RequestMethod.GET)
    @ResponseBody
    public String getProducts() {
    return "List of products";
    }

      @RequestMapping(value = "/products", method = RequestMethod.POST)
      @ResponseBody
      public String addProduct() {
          return "Product added";
      }
    

    }

在上述代码中,getProducts 方法处理 /products 的 GET 请求,addProduct 方法处理 /products 的 POST 请求。

2.2 @GetMapping@PostMapping@PutMapping@DeleteMapping@PatchMapping
  • 作用 :这些注解是 @RequestMapping 的派生注解,分别对应 HTTP 的 GET、POST、PUT、DELETE、PATCH 请求方法,使代码更加简洁易读。

  • 示例

    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class BookController {
    @GetMapping("/books")
    public String getBooks() {
    return "List of books";
    }

      @PostMapping("/books")
      public String addBook() {
          return "Book added";
      }
    
      @DeleteMapping("/books/{id}")
      public String deleteBook(@PathVariable("id") int id) {
          return "Book with id: " + id + " deleted";
      }
    

    }

这里分别使用了 @GetMapping@PostMapping@DeleteMapping 注解来处理不同类型的请求。

3. 请求参数绑定注解

3.1 @RequestParam
  • 作用:用于将请求参数绑定到控制器方法的参数上。可以指定请求参数的名称、是否为必需参数、默认值等。

  • 示例

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class SearchController {
    @GetMapping("/search")
    public String search(@RequestParam("keyword") String keyword,
    @RequestParam(value = "page", defaultValue = "1") int page) {
    return "Searching for: " + keyword + " on page: " + page;
    }
    }

在这个例子中,keyword 是必需的请求参数,page 是可选参数,默认值为 1。

3.2 @PathVariable
  • 作用:用于从请求的 URL 路径中提取变量值,并绑定到控制器方法的参数上。通常用于 RESTful 风格的 URL 中。

  • 示例

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class OrderController {
    @GetMapping("/orders/{orderId}")
    public String getOrder(@PathVariable("orderId") int orderId) {
    return "Order with id: " + orderId;
    }
    }

这里从 URL /orders/{orderId} 中提取 orderId 并绑定到方法参数上。

3.3 @RequestBody
  • 作用:用于将 HTTP 请求的主体内容(如 JSON、XML 等)绑定到控制器方法的参数上。通常用于处理 POST、PUT 等请求中的请求体数据。

  • 示例

    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;

    class User {
    private String name;
    private int age;

      // Getters and Setters
      public String getName() {
          return name;
      }
    
      public void setName(String name) {
          this.name = name;
      }
    
      public int getAge() {
          return age;
      }
    
      public void setAge(int age) {
          this.age = age;
      }
    

    }

    @RestController
    public class UserController {
    @PostMapping("/users")
    public String createUser(@RequestBody User user) {
    return "User created: " + user.getName() + ", age: " + user.getAge();
    }
    }

在这个例子中,客户端发送的 JSON 数据会被自动映射到 User 对象上。

4. 响应相关注解

4.1 @ResponseBody
  • 作用 :用于将控制器方法的返回值直接作为 HTTP 响应体返回,而不经过视图解析器解析为视图。通常与 @Controller 注解一起使用,或者使用 @RestController 注解替代。

  • 示例

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    public class JsonController {
    @RequestMapping("/json")
    @ResponseBody
    public String getJson() {
    return "{"message": "This is a JSON response"}";
    }
    }

4.2 @ResponseStatus
  • 作用:用于指定控制器方法返回的 HTTP 响应状态码。可以在方法或类上使用。

  • 示例

    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ResponseStatus;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class StatusController {
    @GetMapping("/notfound")
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String notFound() {
    return "Resource not found";
    }
    }

在这个例子中,notFound 方法返回的 HTTP 状态码为 404。

5. 其他注解

5.1 @ModelAttribute
  • 作用:有两种主要用途。一是在方法参数上使用时,用于从请求参数、表单数据等中获取数据并绑定到模型对象上;二是在方法上使用时,用于将方法的返回值添加到模型中。

  • 示例

    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RestController;

    class Product {
    private String name;
    private double price;

      // Getters and Setters
      public String getName() {
          return name;
      }
    
      public void setName(String name) {
          this.name = name;
      }
    
      public double getPrice() {
          return price;
      }
    
      public void setPrice(double price) {
          this.price = price;
      }
    

    }

    @RestController
    public class ProductController {
    @GetMapping("/products/add")
    public String addProduct(@ModelAttribute Product product, Model model) {
    model.addAttribute("product", product);
    return "Product added: " + product.getName() + ", price: " + product.getPrice();
    }

      @ModelAttribute("welcomeMessage")
      public String getWelcomeMessage() {
          return "Welcome to our product page";
      }
    

    }

在这个例子中,addProduct 方法使用 @ModelAttribute 将请求参数绑定到 Product 对象上,getWelcomeMessage 方法使用 @ModelAttribute 将返回值添加到模型中。

5.2 @SessionAttributes
  • 作用 :用于指定哪些模型属性应该存储在会话中,以便在多个请求之间共享。通常与 @ModelAttribute 一起使用。

  • 示例

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.SessionAttributes;

    @Controller
    @SessionAttributes("user")
    public class SessionController {
    @GetMapping("/setUser")
    public String setUser(@ModelAttribute("user") String user, Model model) {
    model.addAttribute("user", user);
    return "User set in session: " + user;
    }

      @GetMapping("/getUser")
      public String getUser(@ModelAttribute("user") String user) {
          return "User retrieved from session: " + user;
      }
    

    }

在这个例子中,user 属性被存储在会话中,在 setUser 方法中设置,在 getUser 方法中获取。

相关推荐
violin-wang1 小时前
Intellij IDEA如何查看当前文件的类
java·ide·intellij-idea
圆圆同学1 小时前
Springboot实现TLS双向认证
java·spring boot·后端
大地爱1 小时前
基于SpringBoot和PostGIS的各国及所属机场信息检索及可视化实现
java·spring boot·spring
荔枝味啊~1 小时前
杭州某小厂面试
java·网络·数据库·tcp/ip·面试
九圣残炎2 小时前
【异常记录Java-20250204】调用讯飞星火AI(Spark lite 版本)Api 授权错误问题处理
java·人工智能·spring·spark
神秘的t2 小时前
javaEE初阶————多线程初阶(3)
java·开发语言
liuhaikang2 小时前
【鸿蒙HarmonyOS Next实战开发】实现组件动态创建和卸载-优化性能
java·前端·数据库
m0_748246872 小时前
【springboot】Spring 官方抛弃了 Java 8!新idea如何创建java8项目
java·spring boot·spring
l and3 小时前
Android LifecycleOwner 闪退,java 继承、多态特性!
android·java