问题描述
我的用于记录页面视图的servletfilter接收到具有单个页面请求的GET和POST。我追溯到在页面支持bean上使用Omnifaces ViewScope。
@Named
@org.omnifaces.cdi.ViewScoped
我碰巧注意到日志文件中有确切时间戳的双页视图。使用以下简化版本进行调试,在单个页面请求上,doFilter执行两次,第一次是GET,而URL是我正在浏览的URL。然后再次执行doFilter,它是一个POST,URL是我来自的页面。如果我刷新页面,我会看到一个GET,然后看到同一页面的POST。如果我使用javax.faces.view.ViewScoped
,则只有GET请求进入。
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,servletexception {
HttpServletRequest httpRequest = (HttpServletRequest) request;
System.out.println(new java.util.Date() + " " + ((HttpServletRequest) request).getmethod() + " " + httpRequest.getServletPath());
chain.doFilter(request,response);
}
例如,如果我正在查看http:// localhost:8080 / myApp / page1.xhtml,并且将URL更改为page2.xhtml
过滤器会写出
Wed Aug 26 12:17:04 EDT 2020 GET /page2.xhtml
Wed Aug 26 12:17:04 EDT 2020 POST /page1.xhtml
也许是设计使然?。但是我只想记录用户正在浏览的页面,而不是他们来自的页面。简单吗?
if(((HttpServletRequest) request).getmethod().equalsIgnoreCase("GET")){
//Write to actual log file
}
解决方法
这确实是设计使然。前一页上的POST基本上会发送一个信号,表明该页面已被卸载,因此@ViewScoped
背后的逻辑知道它必须立即破坏JSF视图状态和物理bean。
另请参见the documentation:
...此CDI视图作用域注释将确保在浏览器卸载时也调用
@PreDestroy
注释方法。此技巧由navigator.sendBeacon
完成。对于不支持navigator.sendBeacon
的浏览器,它将回退到同步XHR请求。
要在过滤器中检测到它们时,可以使用ViewScopeManager#isUnloadRequest()
。
if (!ViewScopeManager.isUnloadRequest(request)) {
// Write to actual log file.
}
chain.doFilter(request,response); // Ensure that this just continues!
很显然,这确实没有足够的文档记录,在下一个版本中,我会牢记这一点。