主要思路:在controller層我們將錯誤信息put進map中,然后通過視圖解析器跳轉到目標頁面,在目標頁面中在通過指定標簽內的th:text將錯誤消息取出。
例:
1.編寫controller代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
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 style="color: red" 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的內置對象,可以對字符串內容進行操作。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/bear7/p/13473135.html