Spring Boot 3---Controller使用案例

来源:互联网 发布:mysql 特殊字符入库 编辑:程序博客网 时间:2024/06/05 18:22

1、Spring Boot的Controller使用

(1)@Controller ---处理http请求

(2)@RestController---Spring4之后新加的注解,原来返回json需要 @ResponseBody配合@Controller

(3)RequestMapping配置url映射

(4)PathVariable获取url中的数据

(5)RequestParam获取请求参数的值

(6)GetMapping  组合注解

2、案例

GirlProperties.java(在src/main/java/com.example包中)

package com.example;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component@ConfigurationProperties(prefix="girl")public class GirlProperties {    private String cupSize;    private Integer age;    public String getCupSize() {        return cupSize;    }    public GirlProperties setCupSize(String cupSize) {        this.cupSize = cupSize;        return this;    }}

application.yml(在src/main/resources包下)

server:  port: 8081girl:  cupSize: B  age: 18

GirlController.java

package com.example;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@ResponseBodypublic class GirlController {    @Autowired   private GirlProperties girlProperties;    @RequestMapping(value="/hello")    public String say() {        return girlProperties.getCupSize();    }}

GirlApplication.java

package com.example;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication//开启自动配置public class GirlApplication {   //main方法作用:作为项目启动的入口   public static void main(String[] args) {      SpringApplication.run(GirlApplication.class, args);   }}

运行GirlApplication.java结果:







0 0
原创粉丝点击