目錄:【持續更新。。。。。】
spring 部分常用注解
spring boot 學習之路1(簡單入門)
spring boot 學習之路2(注解介紹)
spring boot 學習之路3( 集成mybatis )
spring boot 學習之路4(日志輸出)
spring boot 學習之路5(打成war包部署tomcat)
spring boot 學習之路6(定時任務)
spring boot 學習之路6(集成durid連接池)
spring boot 學習之路7(靜態頁面自動生效問題)
spring boot 學習之路8 (整合websocket(1))
spring boot 學習之路9 (項目啟動后就執行特定方法)
1. @RestController 和@Controller
控制器Controller 負責處理由DispatcherServlet 分發的請求,它把用戶請求的數據經過業務處理層處理之后,返回給前台頁面
@Controller 的作用 :聲明這是一個controller類,然后使用@RequestMapping ,@ResponseBody等一些注解用以定義URL 請求和Controller 方法之間的映射,使Controller 被前端訪問。
@Controller public class AnnotController { @ResponseBody @RequestMapping("/hello") public String hello() { return "Hello huhy"; } }
@RestController : 從spring4.0版本開始出現.看下圖的官方解釋,會發現,@RestController 其實已經包含了@Controller 和@ResponseBody ,會默認使用@ResponseBody(可以參考spring boot語法)

@RestController public class AnnotController{
@RequestMapping("/hello")
public String hello() {
return "Hello huhy";
}
}
注意 : 其中
@ResponseBody會處理返回的數據格式,使用了該類型注解后返回的不再是視圖,不會進行轉跳,而是返回json或xml數據格式,輸出在頁面上。
如果在類上使用@Controller注解, 可以在需要的方法上單獨添加@ResponseBody ,而使用@RestController相當於在所有的方法上都默認使用了@ResponseBody注解
2. @RequestParam(?傳值) @RequestBody(指定返回的結果以json或者xml形式) @PathVariable(地址欄傳參,常見的是restful風格) 常用參數綁定注解
①@PathVariable 直接通過URL傳參時使用,URL形式:http://localhost:port/path/參數
@RestController @RequestMapping("demoAnnot") public class testController { @RequestMapping(value = "/hello/{name}/{age}", method = RequestMethod.GET) public String hello(@PathVariable("name") String name,@PathVariable("age") int myAge) { return "我是" + name +"年齡 " + myAge; } }
注意: 通過@PathVariable("***")的形式可以獲取指定URL中的參數,此時可以修改變量的名字,如上面的age參數, 如果不需要修改參數名則可以按照URL中參數的順序寫成如下形式
public String hello(@PathVariable String name,@PathVariable int age)
如果是類上面的@RequestMapping("demoAnno") 也添加一個參數,和方法上的獲取使用是一樣的
②@RequestParam也是通過把參數綁定到URL中,但是和@PathVariable有不同,形式為http://localhost:port/path?參數名=參數
@RestController @RequestMapping("demoAnno") public class testController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello(@RequestParam(value = "name", required = false, defaultValue = "null") String name) { return "我是" + name ; } }
注意:@RequestParam中required是"是否必填", "false" 可以不帶此參數, "defaultValue" 可以賦一個默認值.如果選擇required = false ,URL中不帶
name=tom參數,不會報錯. 如果寫成@RequestParam(value = "name") 這樣的形式,則不帶
name=tom參數就會報錯.
③@RequestBody可以將請求體中的JSON字符串綁定到相應的bean上,也可以將其分別綁定到對應的字符串上。
@RestController @RequestMapping("demoAnno") public class testController { @RequestMapping(value = "/hello", method = RequestMethod.POST) public String hello(@RequestBody RequestOrderVo requestOrderVo) { return "我是" + requestOrderVo.getName +"年齡 "+requestOrderVo.getAge; } }