SpringBoot下的SpringMVC和之前的SpringMVC使用是完全一樣的,主要有以下注解:
1.@Controller
Spring MVC的注解,處理http請求
2.@RestController
Spring4后新增注解,是@Controller注解功能的增強,是@Controller與@ResponseBody的組合注解;
如果一個Controller類添加了@RestController,那么該Controller類下的所有方法都相當于添加了@ResponseBody注解;
用于返回字符串或json數據。
案例:
• 創建MyRestController類,演示@RestController替代@Controller + @ResponseBody
@RestController
public class MyRestController {
@Autowired
private StudentService studentService;
@RequestMapping("/boot/stu")
public Object stu(){
return studentService.getStudentById(1);
}
}
• 啟動應用,瀏覽器訪問測試
3.@RequestMapping(常用)
支持Get請求,也支持Post請求
4.@GetMapping
RequestMapping和Get請求方法的組合只支持Get請求;Get請求主要用于查詢操作。
5.@PostMapping
RequestMapping和Post請求方法的組合只支持Post請求;Post請求主要用戶新增數據。
6.@PutMapping
RequestMapping和Put請求方法的組合只支持Put請求;Put通常用于修改數據。
7.@DeleteMapping
RequestMapping 和 Delete請求方法的組合只支持Delete請求;通常用于刪除數據。
項目名稱:013-springboot-springmvc項目集成springmvc
項目作用:演示常見的SpringMVC注解
1.創建一個MVCController,里面使用上面介紹的各種注解接收不同的請求
/**
* 該案例主要演示了使用Spring提供的不同注解接收不同類型的請求
* Created by Felix on 2019/1/23
*/
//RestController注解相當于加了給方法加了@ResponseBody注解,所以是不能跳轉頁面的,只能返回字符串或者json數據
@RestController
public class MVCController {
/**
*以前我們通過method屬性指定請求的方式
* @RequestMapping即支持get又支持post
* 不寫method默認就是
*/
@RequestMapping(value="/boot/req",method = {RequestMethod.GET,RequestMethod.POST})
public Object req(){
return "req";
}
/**
* 只支持get
*/
@GetMapping("/boot/get")
public Object get(){
return "get";
}
/**
* 只支持post
*/
@PostMapping("/boot/post")
public Object post(){
return "post";
}
/**
* 只支持put
*/
@PutMapping("/boot/put")
public Object put(){
return "put";
}
/**
* 只支持delete
*/
@DeleteMapping("/boot/delete")
public Object delete(){
return "delete";
}
}
2.啟動應用,在瀏覽器中輸入不同的請求進行測試
3.Http接口請求工具Postman介紹
因為通過瀏覽器輸入地址,默認發送的只能是get請求,通過Postman工具,可以模擬發送不同類型的請求,并查詢結果,在安裝的時候,有些機器可能會需要安裝MicroSort .NET Framework。
4.使用Postman對其它請求類型做個測試。