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

相关推荐
anOnion7 小时前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
用户47949283569158 小时前
claude Fable用不了?把Gpt 5.5pro接到你的claude code里
前端·后端
zhangxingchao10 小时前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒12 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
nanxun88613 小时前
记一次诡异的 Docker 容器"串包"故障排查
java
Pedantic13 小时前
SwiftUI 手势笔记
前端·后端
橙子家13 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user205855615181313 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州13 小时前
CSS aspect-ratio 属性完全指南
前端