当我成功登录(使用logincontroller)时,我可以看到会话属性“user”的值。
例如:
- 在logincontroller中 -
@RequestMapping(value = "/login", method=RequestMethod.POST)
public String logIn(HttpServletRequest request, HttpServletResponse response, ModelMap map){
String email = request.getParameter("email");
String password = request.getParameter("password");
System.out.println("Login function is called.");
List<UsersModule> list = loginModuleService.getLoginDetails(email,password);
UsersModule foundEntity = new UsersModule();
HttpSession session = null;
if(!list.isEmpty() && email != null && !email.equals("") && !email.trim().equals("") && password != null && !password.equals("") && !password.trim().equals("")){
//ignores multiple results
foundEntity = list.get(0);
session = request.getSession();
session.setAttribute("user", foundEntity.getFamilyName()+", "+foundEntity.getFirstName());
session.setMaxInactiveInterval(60*60);
return "home";
}else{
System.out.println("Empty? "+Boolean.toString(list.isEmpty()));
System.out.println("Email "+email);
System.out.println("Password "+password);
map.addAttribute("error", "Incorrect Email/Password");
return "login";
}
}
- 在home.jsp -
我可以在页面中看到用户值。
但是当我转到另一个页面(使用另一个控制器)时,它会重定向到登录页面。我认为这是因为会话属性“user”为空。我设置了一个条件,如果user为null,它将返回登录页面。
- 另一个控制器 -
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String Home(HttpServletRequest request,
HttpServletResponse response, ModelMap map) {
HttpSession session= request.getSession();
boolean isLogged= session.getAttribute("user")!=null;
if(isLogged){
return "home";
}else{
return "/index"; // redirect to login page if session is not established
}
}
@RequestMapping("/list")
public String list(HttpServletRequest request,
HttpServletResponse response, ModelMap map) {
HttpSession session= request.getSession();
boolean isLogged=session.getAttribute("user")!=null;
if(isLogged){
String searchTerm = request.getParameter("searchTerm");
String paging = request.getParameter("paging");
int page = 0; //pagination not yet working
List<UsersModule> list = usersModuleService.getUsersList(searchTerm,
page);
map.addAttribute("usersList", list);
return "usersmodule/list"; // go to users list page
}else{
return "/index"; // redirect to login page if session is not established
}
}
- list.jsp -
当我转到这样的另一个页面时,我看不到用户值,我被重定向到登录页面。
我无法解决在转到其他网页时如何保留会话属性值。我已经尝试了所有可以找到的资源,但它仍然是一样的。 :(
答案 0 :(得分:0)
public String logIn(HtppSession session,HttpServletRequest request,HttpServletResponse response,ModelMap map){}
将HttpSession定义为登录方法的变量。