前言
前些天在做一個spring boot專案的時候,在后臺傳送json資料給前端的時候,遇到了一些小問題,總結了一下網上的幾種容易犯錯的情況,寫個博客記錄一下
注意事項
-
第一個注意事項是@Autowired的注解
- Service層或者Controller層實作類未添加注解@Autowired
- @Autowired的作用是自動注入依賴的Bean
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
}
- 第二個注意事項是Controller層的注解
- 回傳json資料要用@RestController注解,不能用@Controller注解
- @RestController注解,相當于@Controller+@ResponseBody兩個注解的結合
- 使用@RestController這個注解,就不能回傳jsp或者html頁面,因為視圖決議器無法決議jsp或者html頁面
@Controller
public class HelloController {
@Autowired
UserService userService;
}
@RestController
public class JSONController {
@Autowired
UserService userService;
}
- 第三個注意事項是物體類未寫Getter方法
- 物體類必須要寫Getter方法,否則拿不出資料
報錯情況
- 為什么會報錯
- 查詢一條資料,但回傳兩條資料;
- 查詢多條資料,但是前臺限制只能查詢一條;
解決方法
- 控制查詢與回傳的資料數量必須一致;
- 如果讀者想回傳多條資料,可以將json資料存到list,map等資料結構,回傳list,map等資料結構;
寫在最后
本人是即將大三的廢物蒟蒻一個,若有問題歡迎指正與討論,感謝三連

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/291476.html
標籤:其他
上一篇:行程、執行緒
下一篇:單鏈表的實作
