个人代码Bug:在重定向的情况下,为什么Session数据传不到前端,无法用Thymeleaf来获得?
最近在写一个练手小项目,在写用户登录模块的时候,把以前写好的代码直接拿过来修修改改再用,但是莫名其妙前端无法获得Session数据;
参考部分代码:
@Controller
@SessionAttributes(value = {"userName"})
public class EditorController {
@Autowired login_logoutServiceImpl login_logoutServiceImpl;
@RequestMapping("/login")
public String login(Users users1,Model model1){
//查询出的结果放进去;
Users login_logout_users = login_logoutServiceImpl.setUsersName(users1);
if(users1.getPassword().equals(login_logout_users.getPassword())){
model1.addAttribute("userName", login_logout_users.getName());
return "redirect:index";
}else
return "redirect:Error";
}
前端:`
<span th:if="${userName} == null">
<button type="button" style="width:80px;height:30px;" onclick="Show();">登录/注册</button>
</span>
<span th:if="${userName} != null">
<form th:action="@{/login}" method="post">
<center>
<input type="hidden" th:name="${userName}"/>
<input type="submit" style="width:40px;height:30px;" th:value="${userName}"/>
</center>
</form>
</span>
Bug描述:
按以上代码运行,除了前端无法获取userName之外一切正常;
问题解决:
怎么也没找到原因,最后我把处理用户登录的控制器类塞进了包含index.html文件跳转的控制器类才解决了这个问题;
原因:
之后查出是SessionID的变化,导致前端和后端的Session不是同一个,可以直接把需要重定向的方法和重定向返回的那个页面的方法放一起;比如,重定向到index.html,那么就和Localhost:8080/index,这个URL映射的方法放到一个控制器类中;