Spring Boot 的控制器--Controller

Controller基础

@RestController处理http请求,其实相当于@Controller和@ResponseBody组合。
@RequestMapping配置url映射

使用模板templates

1、加maven依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。

2、Controller上只使用@Controller
3、工程resources目录下,templates目录下新建*.html。
4、url映射的方法中返回上一步的文件名。

前后端分离来进行开发,后端只提供数据,所以不推荐使用

url映射相关的注解

@PathVariable获取路径中的值,这是RESTful方式

    @RequestMapping(value = "/person/{name}",method = RequestMethod.GET)
    public String person(@PathVariable("name") String name){
//        http://localhost:8060/girl/person/kakaluote
        return "say hello to " + name;
    }

@RequestParam获取路径中的值,传统方式,post和get都一样

    @RequestMapping(value = "/person",method = RequestMethod.GET)
    public String book(@RequestParam("book") String book){
//        http://localhost:8060/girl/person?book=java
        return "say hello to " + book;
    }

@RequestParam设置默认值

    @RequestMapping(value = "/man",method = RequestMethod.GET)
    public String bookOne(@RequestParam(value = "book",required = false,defaultValue = "spring boot") String book){
        //required表示是否必传
//        http://localhost:8060/girl/man
//        http://localhost:8060/girl/man?book=java
        return "say hello to " + book;
    }

@RequestMapping每次都写method比较麻烦,用@GetMapping和@PostMapping等替代,方便很多

    @GetMapping(value = "/weather/get")
    public String getWeather(){
        return "qinglang";
    }

    @PostMapping(value = "/weather/post")
    public String postWeather(){
        return "xiayu";
    }

源码

Spring Boot基础

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值