Spring boot(二)

1.Controller的使用

常用注解
这里写图片描述

1.1.@Controller

需要配合模版使用
在pom.xml中加入依赖

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

在resource下面创建templates文件夹,创建index.html
直接在controller中写如下格式:

@Controller
public class HelloController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return "index";
    }
}

即可跳转到index页面
对于目前前后端分离的开发趋势,不建议采用thymeleaf的依赖形势,会影响性能。

1.2.@RestController

@RestController = @Controller+@ResponseBody

@Controller
@ResponseBody
public class HelloController {


    @Autowired
    private DbConfig dbConfig;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return "Hello Spring Boot" + dbConfig.getUrl();
    }
}

为了简洁常采用@RestController

1.3.@RequestMapping

对于多映射多访问url,采用如下格式

@RequestMapping(value = {"/hello","/hi"}, method = RequestMethod.GET)

也可以在类上面写@RequestMapping
格式如下:

@RestController
@RequestMapping(value = "/hello")
public class HelloController {
   @Autowired
    private DbConfig dbConfig;
    @RequestMapping(value = "/say", method = RequestMethod.GET)
    public String say() {
        return "Hello Spring Boot" + dbConfig.getUrl();
    }
}

Url中参数的注解

1.4.@PathVariable

获取url中的数据

@RestController
@RequestMapping(value = "/hello")
public class HelloController {

    @RequestMapping(value = "/say/{id}", method = RequestMethod.GET)
    public String say(@PathVariable("id") Integer id) {
        return "id" + id;
    }
}

访问地址:
http://localhost:8081/molly/hello/say/34

1.5.@RequestParam

获取请求参数的值

@RestController
@RequestMapping(value = "/hello")
public class HelloController {
    @RequestMapping(value = "/say", method = RequestMethod.GET)
    public String say(@RequestParam("id") Integer myid) {
        return "id:" + myid;
    }
}

访问地址:
http://localhost:8081/molly/hello/say?id=39

id也可以不传入,格式如下

@RestController
@RequestMapping(value = "/hello")
public class HelloController {
    @RequestMapping(value = "/say", method = RequestMethod.GET)
    public String say(@RequestParam(value = "id",required = false,defaultValue = "0") Integer id) {
        return "id:" + id;
    }
}

required必填标志,defaultValue默认值

1.6.@GetMapping

组合注解
简化mapping注解

@RequestMapping(value = "/say", method = RequestMethod.GET)等同于
@GetMapping(value = "/say")
同理还有@PostMapping(value = "/say")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值