Tommonkey

All greatness comes from a brave beginning

0%

Java中的控制器和注解学习

在Java编程中,注解(Annotations)是一种元数据机制,用于在代码中添加额外的信息,这些信息可以在编译时或运行时由工具或框架使用。注解不直接影响代码的逻辑功能,但它们可以用于提供描述性信息、控制代码的生成、配置框架行为等。注解通常用于标注类、方法、字段、参数等。下面简单列举了一些注解的作用与如何自定义一个注解。

@RequestMapping

@RequestMapping 是 Spring 框架中的一个注解,用于将 HTTP 请求映射到处理请求的处理方法上。它可以用在类或方法上,为控制器定义特定的 URL 路径,从而处理来自客户端的 HTTP 请求。

常见用法-在类上使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Controller
@RequestMapping("/users")
public class UserController {

@RequestMapping("/list")
public String listUsers() {
// 处理 "/users/list" 请求
return "userList";
}

@RequestMapping("/detail")
public String userDetail() {
// 处理 "/users/detail" 请求
return "userDetail";
}
}

在这个例子中,/users 是所有方法的基础 URL。

常见用法-在方法中使用

在方法上使用 @RequestMapping 注解可以进一步细化路径,并指定 HTTP 方法类型。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Controller
@RequestMapping("/users")
public class UserController {

@RequestMapping(value = "/list", method = RequestMethod.GET)
public String listUsers() {
// 处理 GET 请求 "/users/list"
return "userList";
}

@RequestMapping(value = "/detail", method = RequestMethod.POST)
public String userDetail() {
// 处理 POST 请求 "/users/detail"
return "userDetail";
}
}

结合类和方法上的注解

类和方法上的 @RequestMapping 注解可以结合使用,从而精确地定义请求路径。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Controller
@RequestMapping("/users")
public class UserController {

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String getUser(@PathVariable("id") int id) {
// 处理 GET 请求 "/users/{id}"
return "userDetail";
}

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable("id") int id) {
// 处理 DELETE 请求 "/users/{id}"
return "userDeleted";
}
}

RequestMapping支持的属性

  • value:定义 URL 路径,可以是单个值或数组。
  • method:定义 HTTP 请求方法,如 GET, POST, PUT, DELETE 等。
  • params:定义请求参数的条件,支持简单表达式。
  • headers:定义请求头的条件,支持简单表达式。
  • consumes:指定可接受的请求内容类型(例如 application/json)。
  • produces:指定响应的内容类型(例如 application/json)。

完整代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Controller
@RequestMapping("/products")
public class ProductController {

// 处理 "/products" 的 GET 请求
@RequestMapping(method = RequestMethod.GET)
public String listProducts() {
return "productList";
}

// 处理 "/products" 的 POST 请求
@RequestMapping(method = RequestMethod.POST)
public String addProduct() {
return "productAdded";
}

// 处理 "/products/{id}" 的 GET 请求
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String getProduct(@PathVariable("id") int id) {
return "productDetail";
}

// 处理 "/products/{id}" 的 PUT 请求
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String updateProduct(@PathVariable("id") int id) {
return "productUpdated";
}

// 处理 "/products/{id}" 的 DELETE 请求
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteProduct(@PathVariable("id") int id) {
return "productDeleted";
}
}

@ActionAuth

ActionAuth 是一个自定义注解,通常用于 Java 应用程序中进行权限控制。通过在类或方法上使用 @ActionAuth 注解,可以定义哪些角色或用户组有权访问该类或方法。首先定义一个actionAuth注解:

1
2
3
4
5
6
7
8
9
10
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) // 注解在运行时可用
@Target({ElementType.TYPE, ElementType.METHOD}) // 注解可用于类和方法
public @interface ActionAuth {
String[] roles() default {}; // 允许访问的角色列表
}

接下来在类或方法上使用我们的注解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MyService {

@ActionAuth(roles = {"ADMIN", "USER"})
public void someMethod() {
// 只有具有 ADMIN 或 USER 角色的用户可以访问此方法
System.out.println("Executing someMethod");
}

@ActionAuth(roles = {"ADMIN"})
public void adminMethod() {
// 只有具有 ADMIN 角色的用户可以访问此方法
System.out.println("Executing adminMethod");
}
}

@interface

@interface注解用于定义一个注解类型。注解(Annotation)是Java的一种元数据,可以添加到代码的声明部分,用来提供额外的信息,供编译器、开发工具或运行时使用。以下是@interface注解的一些主要作用和使用方法:

1
2
3
4
5
6
7
8
9
10
11
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value();
int count() default 1;
}

Controller

在使用 Spring 框架进行 Web 应用开发时,Controller 是 MVC(Model-View-Controller)架构中的一个重要组成部分。它负责处理用户的输入,并将其转换为对模型的操作和对视图的更新。其作用主要有以下三点:

  • 处理请求:当用户发送请求(如通过浏览器访问 URL),这些请求会被路由到相应的 Controller 方法中。Controller 是处理 HTTP 请求的核心部分。
  • 协调模型和视图:Controller 调用模型层(即业务逻辑层或数据访问层)来处理数据。处理完数据后,Controller 将数据传递给视图层,以生成用户看到的页面。
  • 定义路由:在 Spring 中,Controller 类和方法通常使用注解来定义路由。例如,@RequestMapping 或 @GetMapping 等注解可以用来映射 URL 请求到特定的方法。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    @RequestMapping("/api")
    public class MyController {

    @GetMapping("/hello")
    @ResponseBody
    public String sayHello() {
    return "Hello, World!";
    }
    }
    备注释义:
  • @Controller:注解用于标记这个类是一个 Spring MVC 的 Controller。
  • @RequestMapping(“/api”):定义类级别的请求路径,这意味着这个 Controller 处理所有以 /api 开头的请求。
  • @GetMapping(“/hello”):定义方法级别的请求路径,这意味着 /api/hello 的 GET 请求会由 sayHello 方法来处理。
  • @ResponseBody:注解表示这个方法的返回值应该直接作为 HTTP 响应的内容,而不是作为视图名解析。

MyAnnotation注解定义了两个元素:value和count。value是一个必需的元素,而count有一个默认值1。

元注解

元注解是用来注解其他注解的注解,Java提供了一些元注解:

  • @Retention: 指定注解的保留策略,取值可以是SOURCE(源代码)、CLASS(字节码)或RUNTIME(运行时)。
  • @Target: 指定注解可以应用的程序元素,比如TYPE(类、接口)、METHOD(方法)、FIELD(字段)等。
  • @Documented: 指定注解是否会包含在Javadoc中。
  • @Inherited: 指定注解是否可以被子类继承。

over~

奖励作者买杯可乐?