目录

Java直通车系列14Spring-MVC深入学习-Controller-编写

Java直通车系列14【Spring MVC】(深入学习 Controller 编写)


基本概念

Controller 是 Spring MVC 架构中的核心组件之一,它负责接收客户端的请求,调用相应的业务逻辑进行处理,并将处理结果返回给客户端。通常,Controller 会根据请求的 URL 和 HTTP 方法,将请求分发到具体的处理方法上。

编写 Controller 的步骤和要点

1. 定义 Controller 类

使用 @Controller 注解标记一个类,表明该类是一个 Spring MVC 的控制器。也可以使用 @RestController 注解,它是 @Controller@ResponseBody 的组合,适用于返回 JSON 或 XML 等数据的场景。

2. 映射请求

使用 @RequestMapping@GetMapping@PostMapping 等注解将 HTTP 请求映射到 Controller 中的具体方法上。这些注解可以指定请求的 URL、HTTP 方法、请求参数等。

3. 处理请求参数

使用 @RequestParam@PathVariable@RequestBody 等注解来获取请求中的参数,并将其绑定到方法的参数上。

4. 调用业务逻辑

在处理方法中调用业务逻辑层(如 Service 层)的方法,完成具体的业务处理。

5. 返回响应

可以返回视图名、 ModelAndView 对象、 ResponseEntity 对象或直接返回数据(使用 @ResponseBody 注解)。

场景示例

1. 简单的 Hello World 示例
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("/hello")
    @ResponseBody
    public String sayHello() {
        return "Hello, World!";
    }
}

解释

  • @Controller 注解标记 HelloController 类为控制器。
  • @GetMapping("/hello") 注解将 /hello 的 GET 请求映射到 sayHello 方法上。
  • @ResponseBody 注解表示方法的返回值将直接作为 HTTP 响应的主体内容返回给客户端。
2. 处理路径变量和请求参数
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @GetMapping("/users/{id}")
    @ResponseBody
    public String getUserById(@PathVariable("id") int userId) {
        return "User ID: " + userId;
    }

    @GetMapping("/search")
    @ResponseBody
    public String searchUsers(@RequestParam("keyword") String keyword) {
        return "Searching for users with keyword: " + keyword;
    }
}

解释

  • @GetMapping("/users/{id}") 定义了一个带有路径变量的请求映射, {id} 表示路径中的变量部分。
  • @PathVariable("id") 注解将路径变量 id 的值绑定到 userId 参数上。
  • @GetMapping("/search") 定义了一个普通的请求映射。
  • @RequestParam("keyword") 注解将请求参数 keyword 的值绑定到 keyword 参数上。
3. 处理表单提交
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class FormController {

    @GetMapping("/form")
    public String showForm() {
        return "form"; // 返回视图名
    }

    @PostMapping("/form")
    public String processForm(@RequestParam("name") String name, @RequestParam("age") int age, Model model) {
        model.addAttribute("name", name);
        model.addAttribute("age", age);
        return "result"; // 返回视图名
    }
}

解释

  • @GetMapping("/form") 处理 GET 请求,返回 form 视图,通常是一个表单页面。
  • @PostMapping("/form") 处理表单提交的 POST 请求,使用 @RequestParam 获取表单数据,并将数据添加到 Model 中,最后返回 result 视图,显示处理结果。
4. 处理 JSON 数据
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class JsonController {

    @PostMapping("/json")
    @ResponseBody
    public ResponseEntity<User> processJson(@RequestBody User user) {
        // 处理用户数据
        return new ResponseEntity<>(user, HttpStatus.OK);
    }
}

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;
    }
}

解释

  • @PostMapping("/json") 处理 POST 请求。
  • @RequestBody 注解将请求体中的 JSON 数据转换为 User 对象。
  • ResponseEntity 用于封装响应数据和 HTTP 状态码,将处理后的 User 对象以 JSON 格式返回给客户端。
5. 异常处理
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ExceptionController {

    @GetMapping("/error")
    @ResponseBody
    public String throwException() {
        throw new RuntimeException("Something went wrong!");
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handleException(RuntimeException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

解释

  • @GetMapping("/error") 方法故意抛出一个 RuntimeException
  • @ExceptionHandler(RuntimeException.class) 注解定义了一个异常处理方法,当 Controller 中抛出 RuntimeException 时,会调用该方法进行处理,返回错误信息和 HTTP 状态码 500。

通过以上示例,可以看到 Controller 在不同场景下的编写方式和应用,根据具体的需求选择合适的注解和处理方式,能够高效地处理客户端请求。