1. 程式人生 > >3、@RequestMapping 配置url對映

3、@RequestMapping 配置url對映

@RequestMapping 此註解即可以作用在控制器的某個方法上,也可以作用在此控制器類上。

類級別上新增@RequestMapping註解時,這個註解會應用到控制器的所有處理器方法上。處理器方法上的@RequestMapping註解會對類級別上的@RequestMapping的宣告進行補充。

共分為三種情況:只作用在類上、只作用在方法上、同時作用在類和方法上

1、@RequestMapping只作用在類級別上 不過在方法上面,下面這句話不能少,否則會報錯 @RequestMapping(method = RequestMethod.GET)

@RestController
@SpringBootApplication @RequestMapping(value = "/hello") public class FirstApplication { @RequestMapping(method = RequestMethod.GET) String sayHello() { return "Hello Spring Boot"; } public static void main(String[] args) { SpringApplication.run(FirstApplication.class, args); } }

2、@RequestMapping只作用在處理器方法上

@RestController
@SpringBootApplication
public class FirstApplication {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    String sayHello() {
        return "Hello Spring Boot";
    }
    public static void main(String[] args) {
        SpringApplication.run(FirstApplication.class, args);
    }
}

上面程式碼sayHello所響應的url=localhost:8080/hello 瀏覽器中輸入:http://localhost:8080/hello

3、同時作用在類和方法上

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

    @RequestMapping(value = "/sayHello",method = RequestMethod.GET)
    String sayHello() {
        return "Hello Spring Boot";
    }
    public static void main(String[] args) {
        SpringApplication.run(FirstApplication.class, args);
    }
}

對應url和結果如下: 這裡寫圖片描述