If the user session hasn't expired, then this is normal behavior for web applications. If the session has expired, then you must make sure there is a logged user and that is has the privileges to access to the page he/she's using in the URL. You can achieve this using a Filter.
I'm assuming your web app is on a Java EE 6 container like Tomcat 7 or 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);
}
}
Some implementation for your ControlAccess class:
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;
}
}
While looking for a nice way to explain this, I found a better answer from BalusC (JSF expert). This is JSF 2 based: