如果用户会话没有过期,那么这是 Web 应用程序的正常行为。如果会话已过期,那么您必须确保有一个已登录的用户,并且该用户有权访问他/她在 URL 中使用的页面。您可以使用过滤器来实现此目的。
我假设您的 Web 应用程序位于 Java EE 6 容器上,例如 Tomcat 7 或 GlassFish 3.x:
@WebFilter(filterName = "MyFilter", urlPatterns = {"/*.xhtml"})
public class MyFilter implements Filter {
public void doFilter(
ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//get the request page
String requestPath = httpServletRequest.getRequestURI();
if (!requestPath.contains("home.xhtml")) {
boolean validate = false;
//getting the session object
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpSession session = (HttpSession)httpServletRequest.getSession();
//check if there is a user logged in your session
//I'm assuming you save the user object in the session (not the managed bean).
User user = (User)session.get("LoggedUser");
if (user != null) {
//check if the user has rights to access the current page
//you can omit this part if you only need to check if there is a valid user logged in
ControlAccess controlAccess = new ControlAccess();
if (controlAccess.checkUserRights(user, requestPath)) {
validate = true;
//you can add more logic here, like log the access or similar
}
}
if (!validate) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.sendRedirect(
httpServletRequest.getContextPath() + "/home.xhtml");
}
}
chain.doFilter(request, response);
}
}
您的 ControlAccess 类的一些实现:
public class ControlAccess {
public ControlAccess() {
}
public boolean checkUserRights(User user, String path) {
UserService userService = new UserService();
//assuming there is a method to get the right access for the logged users.
List<String> urlAccess = userService.getURLAccess(user);
for(String url : urlAccess) {
if (path.contains(url)) {
return true;
}
}
return false;
}
}
在寻找解释这一点的好方法时,我从 BalusC(JSF 专家)那里找到了更好的答案。这是基于 JSF 2 的: