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

相关推荐
suaizai_29 分钟前
Fastjson高危漏洞紧急修复指南
spring boot
Java牛马3 小时前
SpringBoot Starter 依赖相关总结
java·spring·springboot·starter·自动装配·依赖
吴声子夜歌3 小时前
Java面试——Spring Cloud原理及应用(二)
java·spring cloud·面试
东小西4 小时前
【SAA实战】第 1 篇:ReactAgent 入门——先撸个"会调工具的助手"跑起来
java·人工智能·spring
Profile排查笔记4 小时前
指纹浏览器哪个好?从 Profile、代理、权限和自动化能力判断是否适合
前端·人工智能·后端·自动化
mqiqe5 小时前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
lzhdim5 小时前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
denggun123455 小时前
yield
前端·数据库·python
前端snow5 小时前
ai agent -- prompt汇总
前端
脉动数据行情5 小时前
Java 实现台股 TWSE/TPEx 行情采集(个股 + K 线)
java·开发语言·twse·tpex·台股