How to redirect user to login page in JSF
I use JSF 2.0 and facelets. I want to login check at ea开发者_运维技巧ch page and redirect to loginpage if it fails...
<%
HttpSession sess = request.getSession(true);
if (sess.getAttribute("userName") == null ) {
%>
<jsp:forward page="/login.xhtml"/>
<%
return;
} else {
// some code
%>
<%-- some other code --%>
<%
}
%>
When I write this code, Netbeans IDE
won't let me.
How can I use this.
Thanks.
I would suggest using a filter instead of jsp. Then, define it as one of the first filters in web.xml.
public class DirectAccessBlockFilter implements Filter {
private String loginPage = "login.xhtml";
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession(false);
if(session.getAttribute("userName") == null && !httpRequest.getServletPath().contains(loginPage)) {
RequestDispatcher dispatcher = request.getRequestDispatcher(loginPage);
dispatcher.forward(request, response);
return;
}
chain.doFilter(request, response);
}
}
You cannot do that. It's completely impossible, because facelets are not JSPs. Scriptlets don't exists.
Besides, this kind of thing should be implemented in a servlet filter, not on individual pages. Furthermore, you should not do it yourself but use one of the freely available mature implementations:
- Apache Shiro
- Spring Security
Don't do it. Facelets is the default view for a reason.
The login check should instead be done in either of the following:
javax.servlet.Filter
javax.faces.event.PhaseListener
Like the others mentioned, you should absolutely not do it this way, even if it was possible.
Facelets is a pure XML document that's parsed by an XML parser for the sole reason of creating the component tree. As such it's only used for component layouting. There is no facility whatsoever to include any kind of scriptlet.
Technically there are a few tricks which more or less would give you the (wrong) idiom you're after. E.g. you could put that code fragment in a backing bean and call it via an EL expression at the start of each page. You could also create a Java based custom component and place that at the start of each page. Finally you could define your own custom EL function containing that code and call that.
But I can't stress enough however that such an approach is plain wrong. Use the filter or phaselistener suggested by mmanco and Bozho. If you can't live with this, then maybe JSF and Facelets is just not the best technology for you and you'll be better off programming in JSP or PHP.
精彩评论