I would like to block the access of some page even if the user knows the url of some pages.
For example, /localhost:8080/user/home.xhtml
(need to do the login first) if not logged then redirect to /index.xhtml
.
How do that in JSF ? I read in the Google that's needed a filter, but I don't know how to do that.
You need to implement the
javax.servlet.Filter
class, do the desired job indoFilter()
method and map it on an URL pattern covering the restricted pages,/user/*
maybe? Inside thedoFilter()
you should check the presence of the logged-in user in the session somehow. Further you also need to take JSF ajax and resource requests into account. JSF ajax requests require a special XML response to let JavaScript perform a redirect. JSF resource requests need to be skipped otherwise your login page won't have any CSS/JS/images anymore.Assuming that you've a
/login.xhtml
page which stores the logged-in user in a JSF managed bean viaexternalContext.getSessionMap().put("user", user)
, then you could get it viasession.getAttribute("user")
the usual way like below:Additionally, the filter also disabled browser cache on secured page, so the browser back button won't show up them anymore.
In case you happen to use JSF utility library OmniFaces, above code could be reduced as below:
See also:
While it's of course legitimate to use a simple Servlet filter, there are alternatives like