0
當我成功登錄(使用logincontroller)時,我可以看到會話屬性「user」的值。會話只能工作一次spring mvc
例如:
- 中的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」爲空。我把一個條件,如果用戶爲空,它會回到登錄頁面。
- 另一個控制器 -
@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--
,當我去到這樣的另一頁,我不能看到用戶價值,我重定向到登錄頁。
我無法解決如何在轉到其他網頁時保留會話屬性值。我嘗試了所有我能找到的資源,但它仍然是一樣的。 :(
你是怎麼弄到的HttpServletRequest? –
等待,我將發佈完整的代碼 – Ruby
我已編輯它 – Ruby