@RequestMapping 和 @RestController注解
上面兩個注解,是Spring MCV最常用的注解。
@RequestMapping , 他是用來注冊接口的路由映射。
路由映射:當一個用戶訪問url時,將用戶的請求對應到某個方法或類的過程叫做路由映射。
@RequestMapping 注解的使用:它既可以又是類,也可以修飾方法,訪問的地址是類的路徑和方法路徑。
但是在這里我們只通過@RequestMapping 是不足以訪問網頁的,還要通過@RestController注解。
@RestController,他包括了@Controller注解和@ResponseController注解。
@Controller注解返回的是視圖 , @ResponseController返回的是各種格式的數據。
在這里我寫簡單的項目,來掩飾一下,怎么使用的。
如代碼:
package com.example.springbootdemo1;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RequestMapping("/hello")
@RestController
public class HelloController {@RequestMapping("/u1")public String sayHi(){return "hello,Spring 111";}@RequestMapping("/u2")public String hello(){return "Hello Spring MVC";}}
我們訪問我們哪個輸入就訪問就行了,根據url的不同,直接訪問。
如圖訪問結果:
@RequestParam注解
使用@RequestParam注解可以對后端的參數重命名,其實就是可以把前端的參數映射到后端來,進而可以對后端的參數,改成自己想要的。
這里寫了一個計算器功能的網頁,結合前端代碼來看一下
如前端后端代碼:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<form action="calc/sum" method="post"><h1>計算器</h1>數字1:<input name="sum1" type="text"><br>數字2:<input name="sum2" type="text"><br><input type="submit" value=" 點擊相加 ">
</form>
</body>
</html>
package com.example.springbootdemo1;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RequestMapping("/calc")
@RestController
public class CalcController {@RequestMapping("/sum")public String sum(@RequestParam(value = "sum1" , required = false) Integer array , Integer sum2){Integer sum = array + sum2;System.out.println(sum);return "計算結果:" + sum;}
}
我們可以發現,sum1這個參數,我們改成了array,注解里的false表示這里不是必傳的參數,默認為true。
如執行結果:
可以看到代碼執行沒有錯誤。
@RequestBodoy注解
在日常的開發中,@RequestBody注解主要就是用來傳遞JOSN格式的數據。
如代碼:
@RestController
@RequestMapping("/users")
public class UserController { @PostMapping("/create") public ResponseEntity<User> createUser(@RequestBody User user) { // 在這里可以使用user對象的屬性進行相應的業務邏輯處理 // 例如保存用戶信息到數據庫 return ResponseEntity.ok(userService.save(user)); }
}
上面是最常用的注解,下面簡單介紹幾個,用的還行的。
@PathVariable,這個注解和字面的意思一樣,綁定請求url的地址。
如代碼:
@RequestMapping("/m8/{id}/{name}")
public String method8(@PathVariable Integer id, @PathVariable("name") String
userName){return "解析參數id:"+id+",name:"+userName;
}
@GetMapping和PostMapping:這兩個注解,和我們看到的一樣,直接確定了請求的類型,是get還是post。這里就不展示代碼了,例在方法上直接寫就行。
@RequestPart:用于上傳文件。
如代碼:
public String getfile(@RequestPart("file") MultipartFile file) throwsIOException {//獲取?件名稱String fileName = file.getOriginalFilename();//?件上傳到指定路徑file.transferTo(new File("D:/temp/" + file.getOriginalFilename()));
return "接收到?件名稱為: "+fileName;
}