如何在重定向的情况下向前端传数据

如何在重定向的情况下向前端传数据

后端:

	//Spring MVC
	import org.springframework.web.servlet.mvc.support.RedirectAttributes;

	//RedirectAttributes attributes 用于接收重定向传递的数据 
	@PostMapping("/login")
	public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
     
        User user = userService.checkUser(username, password);
        if (user != null) {
     
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/index";
        } else {
     
            attributes.addFlashAttribute("message", "用户名和密码错误");//前端可以获取
            return "redirect:/admin";
        }
    }

前端代码:

<form class="ui large form" method="post" action="#" th:action="@{/admin/login}">
           <div class="ui  segment">
             <div class="field">
               <div class="ui left icon input">
                 <i class="user icon">i>
                 <input type="text" name="username" placeholder="用户名">
               div>
             div>
             <div class="field">
               <div class="ui left icon input">
                 <i class="lock icon">i>
                 <input type="password" name="password" placeholder="密码">
               div>
             div>
             <button class="ui fluid large teal submit button">登   录button>
           div>

           <div class="ui error mini message">div>
           <div class="ui mini negative message" th:unless="${#strings.isEmpty(message)}" th:text="${message}">用户名和密码错误div>
form>

你可能感兴趣的:(解决方法,笔记,web,spring,springmvc,java)