Spring Boot

springboot-Controller

2017-07-07  本文已影响142人  inke

Controller

示例:

HelloController

package com.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Value("${age}")
    private Integer age;//@value可以获取application.yml配置的值

    @RequestMapping(value = "/hello")
    public String sayHello() {
        return "hello world age:" + age;
    }
}

application.yml

age: 18

常用注解

@RestController = @Controller + @ResponseBody
@Controller需要返回 template 模版,类似于 Django 的模板。
建议使用@RestController


映射多个路径

@RequestMapping(value = "/hello")
public String sayHello() {
   return "hello world name:" + person.getName() + " , age:" + person.getAge();
}
@RequestMapping(value = {"hello", "hi"})
public String sayHello() {
   return "hello world name:" + person.getName() + " , age:" + person.getAge();
}
@RestController
@RequestMapping(value = "/demo")
public class HelloController {

    @Autowired
    private Person person;

    @RequestMapping(value = {"hello", "hi"})
    public String sayHello() {
        return "hello world name:" + person.getName() + " , age:" + person.getAge();
    }
}

访问方式:

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

    @Autowired
    private Person person;

    @RequestMapping(value = {"hello", "hi"}, method = RequestMethod.GET)
    //@GetMapping(value = "hello")
    public String sayHello() {
        return "hello world name:" + person.getName() + " , age:" + person.getAge();
    }
}

注意:什么都不写,默认是 get 和 post 都可以访问,但是不建议这样做,需要明确指定访问方式。


获取访问参数

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

上一篇下一篇

猜你喜欢

热点阅读