關於前端接口傳遞的方法,推薦按以下使用:
若要在服務器上創建資源,推薦使用POST方法
若要檢索某個資源,推薦使用GET方法
若要更新資源,推薦使用PUT方法
若要刪除某個資源,推薦使用DELETE方法
另外本章主要講述的是關於前后端通信關於對應性,前端為react的View,會分傳遞不同值有不同的處理情況。
首先關於Springboot內的代碼變更都是在IndexController.java內,以下是代碼:
package maven.example.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/index") public class IndexController { @RequestMapping("/home") public String home() { return "Hello World!"; } }
1:傳遞普通類型的數據,如string
前端:
fetch('http://localhost:8080/index/name', {
method:'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
},
body:"firstName=zhu&lastName=yitian",
}).then(response => response.text()).then(data => {
alert(data)
}).catch(function(e){
alert("error:" + e);
})
后台:
@RequestMapping("name")
public String getName(@RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName) {
return firstName + lastName;
}
@RequestParam:用於訪問 Servlet 請求參數。參數值轉換為已聲明的方法參數類型。
2:傳遞Json類型的數據,接收方為類
前端:
let temp = {}; temp.lastName = 'yitian'; temp.firstName = 'zhu'; fetch('http://localhost:8080/index/userName', { method:'post', headers: { 'Content-Type': 'application/json' }, body:JSON.stringify(temp), }).then(response => response.text()).then(data => { alert(data) }).catch(function(e){ alert("error:" + e); })
后台:
IndexController.java
@RequestMapping("userName")
public String getUserName(@RequestBody User user) {
return user.getFirstName() + user.getLastName();
}
User.java
package maven.example.entity; public class User { private String lastName; private String firstName; public String getLastName(){ return lastName; } public void setLastName(String lastName){ this.lastName = lastName; } public String getFirstName(){ return firstName; } public void setFirstName(String firstName){ this.firstName = firstName; } }
3:傳遞Json類型的數據, 接收方為map
前端:
let temp = {}; temp.lastName = 'yitian'; temp.firstName = 'zhu';
fetch('http://localhost:8080/index/mapName', { method:'post', headers: { 'Content-Type': 'application/json' }, body:JSON.stringify(temp), }).then(response => response.text()).then(data => { alert(data) }).catch(function(e){ alert("error:" + e); })
后台:
@RequestMapping("mapName")
public String getMapName(@RequestBody Map<String, String> map) {
return map.get("firstName") + map.get("lastName");
}
4. 上傳單個文件或圖片
前端:
<form>
<input type="file" id="picture" />
<br/>
<button type="button" onClick={this.handleFile}>上傳圖片</button>
</form>
handleFile(){ let picture = document.getElementById("picture").files; let formData = new FormData(); formData.append('file', picture[0]);//這里的file要與后台@RequestParam的參數值相對應 fetch('http://localhost:8080/index/getPicture', { method:'post', body:formData, }).then(response => response.text()).then(data => { alert(data) }).catch(function(e){ alert("error:" + e); }) }
后台:
@RequestMapping("getPicture")
public String handleFormUpload(@RequestParam("file") MultipartFile file) {
try{
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
File picture = new File("temp.png");//這里指明上傳文件保存的地址
FileOutputStream fos = new FileOutputStream(picture);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bytes);
bos.close();
fos.close();
return "success";
}
}catch (IOException e){
System.out.println(e);
}
return "failed";
}
5.上傳多個文件或圖片
前端:
<form>
<input type="file" id="picture" multiple="multiple"/>
<br/>
<button type="button" onClick={this.handleFile}>上傳圖片</button>
</form>
handleFile(){ let picture = document.getElementById("picture").files; let formData = new FormData(); for (let i = 0; i < picture.length; ++i){ formData.append('file', picture[i]); } fetch('http://localhost:8080/index/getPictures', { method:'post', body:formData, }).then(response => response.text()).then(data => { alert(data) }).catch(function(e){ alert("error:" + e); }) }
后台:
@RequestMapping("getPictures")
public String handleFormsUpload(HttpServletRequest request) {
try{
List<MultipartFile>files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
for(int i = 0; i < files.size(); ++i){
file = files.get(i);
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
File picture = new File("temp" + String.valueOf(i) + ".png");//這里指明上傳文件保存的地址
FileOutputStream fos = new FileOutputStream(picture);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bytes);
bos.close();
fos.close();
}
}
return "success";
}catch (IOException e){
System.out.println(e);
}
return "failed";
}
