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

相关推荐
Thexhy6 分钟前
Java大模型后端开发全流程指南
java·ai·大模型
前端摸鱼匠12 分钟前
Vue 3 的watchEffect函数:介绍watchEffect的基本用法和特点
前端·javascript·vue.js·前端框架·ecmascript
拉不动的猪30 分钟前
基本数据类型Symbol的基本应用场景
前端·javascript·面试
從南走到北36 分钟前
JAVA同城服务场馆预约门店预约健身房瑜伽馆预约系统支持H5小程序APP源码
java·开发语言·小程序
韩立学长40 分钟前
【开题答辩实录分享】以《智慧农业信息化服务平台小程序》为例进行答辩实录分享
数据库·spring boot·小程序
爱学的小码44 分钟前
JavaEE初阶——多线程3(案例)
java·开发语言·单例模式·java-ee
جيون داد ناالام ميづ1 小时前
Spring Boot 核心原理(五):配置管理怎么玩?从基础到多环境再到配置中心
java·spring boot·后端
_小九1 小时前
【开源】耗时数月、我开发了一款功能全面【30W行代码】的AI图床
前端·后端·开源
just小千1 小时前
HTML进阶——常用标签及其属性
前端·html
惜.己1 小时前
html笔记(一)
前端·笔记·html