下面是我的代码;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package racms;
import java.io.IOException;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter("/faces/*")
public class AuthenticationFilter implements Filter {
@Override
public void init(FilterConfig config) throws ServletException {
// If you have any <init-param> in web.xml, then you could get them
// here by config.getInitParameter("name") and assign it as field.
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String pageRequested = request.getRequestURI().toString();
//try{
//FacesContext fctx = FacesContext.getCurrentInstance();
//NavigationHandler myNav = fctx.getApplication().getNavigationHandler();
if(session==null){
session = request.getSession(true); // will create a new session
response.sendRedirect("Login.xhtml");
//myNav.handleNavigation(fctx, null, "Login");
}else if(session==null && pageRequested.contains("Login.xhtml")){
// session.getAttribute("user");
chain.doFilter(request, response); // continue filtering
}else if((session.getAttribute("user")== null) && (!pageRequested.contains("Login.xhtml"))){
response.sendRedirect("Login.xhtml");
//myNav.handleNavigation(fctx, null, "Login");
}else {
chain.doFilter(request, response);
}
//}catch(Exception e){
// System.out.println("Error :"+ e);
//}
/*if ((((HttpServletRequest) req).getSession().getAttribute("user") == null)) {
FacesContext fctx = FacesContext.getCurrentInstance();
NavigationHandler myNav = fctx.getApplication().getNavigationHandler();
myNav.handleNavigation(fctx, null, "Login");
//response.sendRedirect(request.getContextPath() + "/Login.xhtml"); // No logged-in user found, so redirect to login page.
} else {
chain.doFilter(req, res); // Logged-in user found, so just continue request.
}*/
}
@Override
public void destroy() {
// If you have assigned any expensive resources as field of
// this Filter class, then you could clean/close them here.
}
}
如果我使用 FacesContext.getCurrentInstance(),会发生 java.lang.Nullpointer 异常;如果我使用 response.sendRedirect("Login.xhtml"); 它显示一个空白页面,如果我查看源代码,我可以在 jsf 中看到 Login.xhtml 的源代码。它不会呈现为 html..
我想要做的是:如果用户未登录并访问任何页面,则将他发送到 Login.xhtml,如果用户在 Login.xhtml 上,则向他显示要登录的页面。
请帮忙..