Springboot中如何通过Map将错误信息有效展示在网页上?

2026-05-21 11:461阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计316个文字,预计阅读时间需要2分钟。

Springboot中如何通过Map将错误信息有效展示在网页上?

主要思路:在controller层,我们将错误信息put进map中,然后通过视图解析器跳转到目标页面。在目标页面中,通过指定标签内的th:text将错误信息取出。

示例:

1.编写controller代码 @PostMapping()

主要思路:在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)

Springboot中如何通过Map将错误信息有效展示在网页上?

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

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

本文共计316个文字,预计阅读时间需要2分钟。

Springboot中如何通过Map将错误信息有效展示在网页上?

主要思路:在controller层,我们将错误信息put进map中,然后通过视图解析器跳转到目标页面。在目标页面中,通过指定标签内的th:text将错误信息取出。

示例:

1.编写controller代码 @PostMapping()

主要思路:在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)

Springboot中如何通过Map将错误信息有效展示在网页上?

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

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