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 等代替。

相关推荐
用户0595401744610 分钟前
LangChain Memory 测试踩坑实录:用 pytest 自动化回归对话记忆,我折腾了整整一个周末
前端·css
coder!mq24 分钟前
说几个常见的语法糖?
java·开发语言·算法
gugucoding26 分钟前
38. 【Java】Stream API(下):高级操作与性能
java·开发语言
kyriewen26 分钟前
Claude Code后天起默认Auto模式了——我第一时间改了这6个设置
前端·ai编程·claude
心平气和量大福大1 小时前
android-实例-蒲公英-更新与安装-5-签名与生成APK
android·java·开发语言
风骏时光牛马1 小时前
智能赋能型AI办公一体化系统架构
前端
满栀5851 小时前
vue动态路由效果
前端·javascript·vue.js·前端框架·vue
952362 小时前
Spring-cloud配置中心
java·spring·spring cloud·微服务
土豆~2 小时前
文件名没后缀就打不开:前端文件预览的内容嗅探改造
前端·状态模式