Springboot如何使用Map將錯誤提示輸出到頁面
主要思路:在controller層我們將錯誤信息put進map中,然后通過視圖解析器跳轉到目標頁面,在目標頁面中在通過指定標簽內的th:text將錯誤消息取出。
例:
1.編寫controller代碼
@PostMapping('/user/login') public String login(@RequestParam('username') String username, @RequestParam('password') String password, Map<String,Object> map ){ if (!StringUtils.isEmpty(username) && '123456'.equals(password)){ return 'dashboard'; }else { map.put('msg','用戶名或密碼錯誤'); return 'login'; } }
代碼解讀:
@PostMapping('/user/login')等價于@RequestMapping(value ='/user/login' ,method = RequestMethod.POST)
2.到目標html頁面取出錯誤提示信息
<p th:text='${msg}' th:if='${not #strings.isEmpty(msg)}'></p>
代碼解讀:
1.th:if 的優先級比 th:text高,所以會先執行th:if中的判斷邏輯,只有th:if中的邏輯為true時才會顯示th:text中的內容。
2.strings是thymeleaf的內置對象,可以對字符串內容進行操作。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. vue實現web在線聊天功能2. JavaEE SpringMyBatis是什么? 它和Hibernate的區別及如何配置MyBatis3. JavaScript實現頁面動態驗證碼的實現示例4. Springboot 全局日期格式化處理的實現5. Java使用Tesseract-Ocr識別數字6. 完美解決vue 中多個echarts圖表自適應的問題7. Python使用urlretrieve實現直接遠程下載圖片的示例代碼8. SpringBoot+TestNG單元測試的實現9. 在Chrome DevTools中調試JavaScript的實現10. 解決Android Studio 格式化 Format代碼快捷鍵問題
