springboot——简单通过Map将错误提示输出到页面显示

时间:2020-08-11 00:25:39   收藏:0   阅读:91

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

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!