我正在尝试在preRenderView侦听器方法中使用authenticate(),以便根据页面中的视图参数有条件地触发身份验证。我尝试添加一个简单的方法:
@Named
@RequestScoped
public class PermissionBean implements java.io.Serializable {
public void preRender() {
System.out.println("IN PRERENDER");
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
request.authenticate(response);
} catch (Exception e) { // may throw ServletException or IOException
e.printStackTrace();
}
}
authenticate方法本身不会抛出异常,它会按预期触发重定向到Login.xhtml。但是,我进入我的服务器日志,我得到了这个例外:
enter code here
INFO: IN PRERENDER
FINEST: GET /Login.xhtml previous[3]
INFO: Exception when handling error trying to reset the response.
java.lang.NullPointerException
at com.sun.faces.facelets.tag.jsf.core.DeclarativeSystemEventListener.processEvent(EventHandler.java:126)
at javax.faces.component.UIComponent$ComponentSystemEventListenerAdapter.processEvent(UIComponent.java:2508)
at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2129)
at com.sun.faces.application.ApplicationImpl.invokeComponentListenersFor(ApplicationImpl.java:2077)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:286)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:244)
at javax.faces.application.ApplicationWrapper.publishEvent(ApplicationWrapper.java:670)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:108)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
所以我的请求没有重定向到Login.xhtml。
我的问题是 - 这是应该在JSF托管bean中运行的东西,还是仅在JSF请求生命周期之外合法?我尝试从WebFilter调用authenticate(),它就像被删除一样。
谢谢, 埃伦
答案 0 :(得分:0)
每当请求被重定向时,您都需要告诉JSF不呈现最初被要求执行的响应。您可以通过检查HttpServletRequest#authenticate()
是否返回false
然后相应地调用FacesContext#responseComplete()
来执行此操作。
if (!request.authenticate(response)) {
FacesContext.getCurrentInstance().responseComplete();
}