SpringBoot入門(二):Controller的使用
阿新 • • 發佈:2018-06-24
config alt pack AI name boot ring ron 關於
Controller中註解的使用:
@Controller
●該註解用來響應頁面,必須配合模板來使用
關於模板的使用,下一節會說到。
@RestController
●該註解可以直接響應字符串,返回的類型為JSON格式
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.RequestMapping; 4 import org.springframework.web.bind.annotation.RestController;View Code5 6 @RestController 7 public class HelloWorldController { 8 9 @RequestMapping("/") 10 public String index() { 11 return "Hello World"; 12 } 13 }
啟動程序,訪問http://localhost:8080/,返回Hello World
@RequestMapping
●指定URL訪問中的前綴
1 package com.example.demo; 2 3 import org.springframework.boot.SpringApplication;View Code4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 6 @SpringBootApplication 7 public class DemoApplication { 8 9 public static void main(String[] args) { 10 SpringApplication.run(DemoApplication.class, args); 11 } 12 }
訪問http://localhost:8080/hello,返回Hello World
@RequestParam
●獲取請求URL中參數的變量
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.RequestMapping; 4 import org.springframework.web.bind.annotation.RequestMethod; 5 import org.springframework.web.bind.annotation.RequestParam; 6 import org.springframework.web.bind.annotation.RestController; 7 8 @RestController 9 public class HelloWorldController { 10 11 @RequestMapping(value="/hello",method=RequestMethod.GET) 12 public String index(@RequestParam("name")String name) { 13 return "Hello World:"+name; 14 } 15 }View Code
訪問http://localhost:8080/hello?name=張三,返回Hello World:張三
@PathVariable
●獲取請求URL中路徑的變量
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.PathVariable; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestMethod; 6 import org.springframework.web.bind.annotation.RestController; 7 8 @RestController 9 public class HelloWorldController { 10 11 @RequestMapping(value="/hello/{name}",method=RequestMethod.GET) 12 public String index(@PathVariable("name")String name) { 13 return "Hello World:"+name; 14 } 15 }View Code
訪問http://localhost:8080/hello/張三,返回Hello World:張三
@GetMapping/@PostMapping
●與RequestMapping類似,不同的是指定了請求的方式(get/post)
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.GetMapping; 4 import org.springframework.web.bind.annotation.RestController; 5 6 @RestController 7 public class HelloWorldController { 8 9 @GetMapping(value="/hello") 10 public String index() { 11 return "Hello World"; 12 } 13 }View Code
總結
Controller是SpringBoot裏比較常用的組件,通過匹配客戶端提交的請求,分配不同的處理方法,然後向客戶端返回結果。
SpringBoot入門(二):Controller的使用