您的位置:首页技术文章
文章详情页

Springboot如何使用Map将错误提示输出到页面

【字号: 日期:2023-04-29 09:07:12浏览:5作者:猪猪

主要思路:在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的内置对象,可以对字符串内容进行操作。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: Spring
相关文章: