spring boot控制器的使用

一:

1.注解

  spring boot控制器的使用_第1张图片

 

2.control注解

  

@Controller
public class HelloController {
    @Value("${cupSize}")
    private String cupSize;

    @Value("${age}")
    private Integer age;
    @Value("${content}")
    private String content;
   @Autowired
   private GirlProperties  girlProperties;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(){
       // return  girlProperties.getCupSize()+" "+girlProperties;
        return "index";
    }
}

  



   org.springframework.boot
   spring-boot-starter-thymeleaf
   true

  spring boot控制器的使用_第2张图片

 

@Controller 与@ResponseBody等价于@RestController

3.hello与hi都可以访问多个浏览器地址映射到一个方法()

@RequestMapping(value = {"/hello","/hi"}

 
   
@RestController
public class HelloController {
   @Autowired
   private GirlProperties  girlProperties;

    @RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)
    public String say(){
        return  girlProperties.getCupSize()+" "+girlProperties;

    }
}

 

4.RequestMapping的类上使用的方式

@RestController
@RequestMapping("/hello")
public class HelloController {
   @Autowired
   private GirlProperties  girlProperties;

    @RequestMapping(value = "/say",method = RequestMethod.GET)
    public String say(){
        return  girlProperties.getCupSize()+" "+girlProperties;

    }
}


 http://127.0.0.1:8081/hello/say

 

二:

1.注解

  spring boot控制器的使用_第3张图片

 

2.PathVariable的使用

http://127.0.0.1:8081/hello/say?id=10这个针对的是?=这种url

   @Autowired
   private GirlProperties  girlProperties;

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

    }
}

 

3.RequestParam的使用

@RestController
@RequestMapping("/hello")
public class HelloController {
   @Autowired
   private GirlProperties  girlProperties;

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

    }
}

 

4.设置默认值

@RequestParam(value = "id",required = false,defaultValue = "0")Integer id

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

   @Autowired
   private GirlProperties  girlProperties;

    @RequestMapping(value = "/say",method = RequestMethod.GET)
    public String say(@RequestParam(value = "id",required = false,defaultValue = "0")Integer id){
        return  Integer.toString(id);

    }
}

 

http://127.0.0.1:8081/hello/say?id=10

http://127.0.0.1:8081/hello/say?id

http://127.0.0.1:8081/hello/say

这三种路径映射的url都不会报错

 

5.GetMapping的使用

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

等价于@GetMapping(value = "/say")

你可能感兴趣的:(spring入门,spring,boot,controller注解)