What is `@Controller` does?

@ControllerSpringMVC注解,标记一个类作为Web控制器(Controller),负责处理HTTP请求并返回响应结果

SpringMVC中,控制器类的主要职责是:
1、接收来自客户端的HTTP请求
2、调用服务层或其他业务逻辑组件
3、根据操作结果准备视图模型数据(Model),将控制权转移给视图解析器(View Resolver)渲染视图
4、操作结果直接返回HTTP响应(例如JSON、XML等)。

使用样例

简单页面渲染

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SimplePageController {
   

    @GetMapping("/hello")
    public String displayHelloPage() {
   
        // ...
        return "hello"; // 假设有一个名为"hello.html"的模板文件在视图解析器配置的路径下
    }
}

结合ModelAndView对象使用

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

@Controller
public class UserViewController {
   

    @GetMapping("/users/{id}")
    public ModelAndView showUser(@PathVariable Long id, Model model) {
   
        // 假设userService.find(id)获取用户信息
        User user = userService.find(id);

        // 将用户信息添加到模型中供视图模板使用
        model.addAttribute("user", user);

        // 返回包含视图名称和模型数据的ModelAndView对象
        return new ModelAndView("user-profile", model.asMap());
    }
}

处理POST请求并返回重定向

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/login")
public class LoginController {
   

    @GetMapping
    public String showLoginForm() {
   
        // 显示登录表单页面
        return "login";
    }

    @PostMapping
    public String processLogin(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              RedirectAttributes redirectAttrs) {
   

        // 假设userService.authenticate(username, password)进行身份验证
        if (userService.authenticate(username, password)) {
   
            // 登录成功,重定向到主页
            redirectAttrs.addFlashAttribute("successMessage", "Welcome, you have successfully logged in!");
            return "redirect:/home";
        } else {
   
            // 登录失败,将错误信息添加到模型中以便在重定向后的页面显示
            redirectAttrs.addFlashAttribute("errorMessage", "Invalid credentials. Please try again.");
            return "redirect:/login";
        }
    }
}

结合@RequestBody处理JSON数据

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

@RestController
public class UserController {
   

    @PostMapping("/users")
    public ResponseEntity<User> createUser(@RequestBody CreateUserRequest request) {
   
        User user = userService.createUser(request.getName(), request.getEmail());
        return ResponseEntity.ok(user);
    }

    static class CreateUserRequest {
   
        private String name;
        private String email;

        // getters and setters
    }
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-19 12:02:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-19 12:02:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-19 12:02:04       87 阅读
  4. Python语言-面向对象

    2024-01-19 12:02:04       96 阅读

热门阅读

  1. R语言入门——多变量移除

    2024-01-19 12:02:04       58 阅读
  2. C语言中链栈的表示和实现

    2024-01-19 12:02:04       53 阅读
  3. centos中安装nfs实现服务器文件共享

    2024-01-19 12:02:04       63 阅读
  4. Vue中Props将父组件的数据传递给子组件

    2024-01-19 12:02:04       57 阅读
  5. Python封装tvdi算法为exe并读取xml

    2024-01-19 12:02:04       63 阅读
  6. Spring Boot多环境配置

    2024-01-19 12:02:04       59 阅读