Spring Boot Controller

刚入门小白,详细请看这篇SpringBoot各种Controller写法_springboot controller-CSDN博客


Spring Boot 提供了@Controller和@RestController两种注解。

@Controller

返回一个string,其内容就是指向的html文件名称。

java 复制代码
@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String index(ModelMap map) {
        map.addAttribute("name", "ge");
        return "hello";
    }
}

@RestController

将返回对象数据转换为JSON格式。

java 复制代码
@RestController
public class HelloController {
    @RequestMapping("/user")
    public User getUser() {
        User user = new User();
        user.setUsername("ge");
        user.setPassword("kaimen");
        return user;
    }
}

@RequestMapping

负责URL路由映射。

如果添加在Controller类上,则该Controller中所有路由映射都会加上该映射规则;

如果添加在方法上,则只对当前方法生效。

属性:value, method, consumes, produces, params, headers 等

java 复制代码
@RequestMapping(value = "/getData", method = RequestMethod.GET)
    public String getData() {
        return "hello";
}

Method 匹配也可以用 @GetMapping, @PostMapping 等代替。

相关推荐
itmigrate8 分钟前
前端项目里,Object.is 并不是 === 的平替
前端
学长毕设1 小时前
基于SpringBoot的青少年编程学习平台系统-附源码
spring boot·学习·青少年编程
文丑颜不良啊1 小时前
LeetCode876~900题目解析
java·leetcode
小大宇1 小时前
Vue知识点6-computed计算属性
前端·javascript·vue.js
程序员海军2 小时前
尤雨溪 : Vue 4 已经在规划中了!
前端·javascript·vue.js
aloha_7892 小时前
Java 基础、集合、异常与 JUnit 5 速查
java·junit·sqlserver
2601_949970692 小时前
HumanizeDuration 跨端三方库仓颉适配全流程
前端·javascript·flutter
知守观2 小时前
设计模式实战:从真实老项目中看标准模板方法与工厂的落地
java·spring·设计模式
独隅3 小时前
Claude API 实战教程:从入门到完整项目
android·java·数据库·claude·claude code
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 圈子功能实现:总结
java·开发语言·交友