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

时间:2021-09-06 07:02:43

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

例:

1.编写controller代码

?
1
2
3
4
5
6
7
8
9
10
11
12
@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 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