2小時學會SpringBoot(4-1)
阿新 • • 發佈:2018-11-24
Controller的使用
Controller | 處理http請求 |
---|---|
@RestController | Spring4之後新加的註解,原來json需要@ResponseBody配合@Controller |
@RequestMapping | 配置url對映 |
thymeleaf瞭解一下即可,現在的開發方式都是前後端分離的。
@RestController等同於@Controller和@ResponseBody
如果希望訪問 http://127.0.0.1:8080/hi
@RequestMapping(value = {"/hello","hi"},method = RequestMethod.GET)
@RequestMapping還有一種使用方式是給整個類使用。
package com.fiona;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private GirlProperties girlProperties;
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say() {
return girlProperties.getCupSize();
}
}
如果要使用除Get以外的其他方式,常用的是Get和Post。改成post請求
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private GirlProperties girlProperties;
@RequestMapping(value = "/say",method = RequestMethod.POST)
public String say() {
return girlProperties.getCupSize();
}
}
瀏覽器訪問 http://127.0.0.1:8080/hello/say 報405。使用postman選擇post方法進行請求。
不寫請求方式,Get和Post均可訪問到,但不推薦。為了安全起見。
@RequestMapping(value = "/say")
@PathVariable | 獲取url中的資料 |
---|---|
@RequestParam | 獲取請求引數的值 |
@GetMapping | 組合註解 |
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/say/{id}",method = RequestMethod.GET)
public String say(@PathVariable("id") Integer id) {
return "id:"+id;
}
}
瀏覽器訪問 http://127.0.0.1:8080/hello/say/23
顯示 id:23
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/{id}/say",method = RequestMethod.GET)
public String say(@PathVariable("id") Integer id) {
return "id:"+id;
}
}
瀏覽器請求 http://127.0.0.1:8080/hello/100/say
顯示 id:100
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(@RequestParam("id") Integer id) {
return "id:"+id;
}
}
瀏覽器請求 http://127.0.0.1:8080/hello/say?id=50
顯示 id:50
@RequestParam(“id”)引號裡面的名字要和瀏覽器的變數名一致,但後面但id可以不叫id,取其他名字也可以。
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(@RequestParam("id") Integer myId) {
return "id:"+myId;
}
}
瀏覽器請求 http://127.0.0.1:8080/hello/say?id=111
顯示 id:111
假如不傳id
給id設定一個預設值為0
@RestController
@RequestMapping("/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;
}
}
可以使用
@GetMapping(value = "/say")
代替
@RequestMapping(value = "/say",method = RequestMethod.GET)
還有 @PostMapping @PutMapping這樣的組合書寫。