springboot输出错误提示 Springboot怎样使用Map将错误提示输出到页面

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot输出错误提示 Springboot怎样使用Map将错误提示输出到页面

白熊啊   2021-03-16 我要评论
想了解Springboot怎样使用Map将错误提示输出到页面的相关内容吗,白熊啊在本文为您仔细讲解springboot输出错误提示的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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 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的内置对象,可以对字符串内容进行操作。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们