What is `@Controller` does?

news/2024/7/7 21:08:32

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


http://lihuaxi.xjx100.cn/news/1966114.html

相关文章

自动化测试理论(1)—概述需要掌握的内容

要在自动化测试领域取得成功&#xff0c;需要掌握一系列技能和概念。以下是一些关键的内容&#xff1a; 编程语言&#xff1a; 了解并精通至少一种编程语言&#xff0c;如Python&#xff0c;Java&#xff0c;JavaScript等。编写自动化测试脚本通常需要编程技能。 自动化测试框…

mysql-bin日志清理,并设置expire_logs_days时间,mysql占用空间过大问题

mysql-bin日志清理&#xff0c;并设置expire_logs_days时间&#xff0c;mysql占用空间过大问题 文章目录 问题查看mysql配置参数解决全局修改参数清理日志规则手动清理my.cnf 外传 问题 最近发现生产环境的服务器磁盘空间吃紧&#xff0c;查下到底是哪里占用的空间比较大&…

App备案中如何查看公钥 SHA1等信息?

在我们App进行备案中&#xff0c;需要提供公钥 SHA1等信息&#xff0c;安卓的都好说&#xff0c;尤其是苹果的&#xff0c;下面开始讲述下如何查看 1.打开初雪云网站&#xff0c;点击“服务内容”-“苹果P12证书在线创建” 2.点击手动创建CSR 3.输入邮箱和名字等等 4.创建完毕后…

安科瑞微电网能量监测系统Acrel-2000MG 储能电站监测预警

在新型电力系统中&#xff0c;储能将成为至关重要的一环&#xff0c;是分布式光伏、风电等新能源消纳以及电网安全保障必要保障&#xff0c;在电源侧、电网侧、用户侧都会得到广泛的应用。《电力现货市场基本规则&#xff08;征求意见稿&#xff09;》以及各地出台的扶持政策给…

全方位提升用户数字化体验的解决方案

前言 在数字化的世界中&#xff0c;用户体验越来越成为企业关注的焦点&#xff0c;然而&#xff0c;用户体验极具主观性&#xff0c;科学地评估用户体验&#xff0c;建立科学的量化体系是难上加难。今天介绍全方位提升用户数字化体验的解决方案&#xff0c;方案通过全面观测用…

OJ14-01

读取字符串abcdefghij&#xff0c;然后层次建树建立一颗二叉树&#xff0c;然后前序遍历输出abdhiejcfg&#xff0c;注意不要打印前序遍历几个汉字 #include <stdio.h> #include <stdlib.h>typedef char BiElemType; typedef struct BiTNode {BiElemType data;str…

git pull 时 配置适合自己的合并策略 git config pull.rebase

当 git pull 时有可能遇到以下的提示 hint: git config pull.rebase false # merge (the default strategy) hint: git config pull.rebase true # rebase hint: git config pull.ff only # fast-forward only这三个配置项影响git pull的默认行为。以下是对它们…

STM32F103标准外设库——认识STM32(一)

个人名片&#xff1a; &#x1f981;作者简介&#xff1a;一名喜欢分享和记录学习的在校大学生 &#x1f42f;个人主页&#xff1a;妄北y &#x1f427;个人QQ&#xff1a;2061314755 &#x1f43b;个人邮箱&#xff1a;2061314755qq.com &#x1f989;个人WeChat&#xff1a;V…