javax.faces.application.ViewExpiredException:无法还原视图 [英] javax.faces.application.ViewExpiredException: View could not be restored

查看:150
本文介绍了javax.faces.application.ViewExpiredException:无法还原视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了具有容器管理的安全性的简单应用程序.问题是当我登录并打开另一个要注销的页面时,然后回到第一页,然后单击任何链接等或刷新页面,我得到此异常.我想这是正常的(或者可能不是:)),因为我注销了,会话被破坏了.我应该怎么做才能将用户重定向到例如index.xhtml或login.xhtml并使他免于看到该错误页面/消息?

I have written simple application with container-managed security. The problem is when I log in and open another page on which I logout, then I come back to first page and I click on any link etc or refresh page I get this exception. I guess it's normal (or maybe not:)) because I logged out and session is destroyed. What should I do to redirect user to for example index.xhtml or login.xhtml and save him from seeing that error page/message?

换句话说,注销后如何自动将其他页面重定向到索引/登录页面?

In other words how can I automatically redirect other pages to index/login page after I log out?

这里是:

javax.faces.application.ViewExpiredException: viewId:/index.xhtml - View /index.xhtml could not be restored.
    at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:212)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:110)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at filter.HttpHttpsFilter.doFilter(HttpHttpsFilter.java:66)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    at java.lang.Thread.run(Thread.java:619)

推荐答案

简介

只要javax.faces.STATE_SAVING_METHOD设置为server(默认值),并且最终用户通过<h:form>使用<h:commandLink><h:commandButton>ViewExpiredException >,而关联的视图状态在会话中不再可用.

Introduction

The ViewExpiredException will be thrown whenever the javax.faces.STATE_SAVING_METHOD is set to server (default) and the enduser sends a HTTP POST request on a view via <h:form> with <h:commandLink>, <h:commandButton> or <f:ajax>, while the associated view state isn't available in the session anymore.

将视图状态标识为<h:form>的隐藏输入字段javax.faces.ViewState的值.将状态保存方法设置为server时,它仅包含引用会话中已序列化视图状态的视图状态ID.因此,当会话由于某种原因而过期时(要么在服务器或客户端超时,要么由于某种原因在浏览器中不再维护会话cookie,或者通过在服务器中调用HttpSession#invalidate(),或者由于服务器特定的错误 WildFly 中已知的会话Cookie ),则会话中的序列化视图状态不再可用,最终用户将获得此异常.要了解会话的工作原理,另请参见 servlet的工作原理?实例化,会话,共享变量和多线程.

The view state is identified as value of a hidden input field javax.faces.ViewState of the <h:form>. With the state saving method set to server, this contains only the view state ID which references a serialized view state in the session. So, when the session is expired for some reason (either timed out in server or client side, or the session cookie is not maintained anymore for some reason in browser, or by calling HttpSession#invalidate() in server, or due a server specific bug with session cookies as known in WildFly), then the serialized view state is not available anymore in the session and the enduser will get this exception. To understand the working of the session, see also How do servlets work? Instantiation, sessions, shared variables and multithreading.

JSF将在会话中存储的视图数量也受到限制.达到限制后,最近最少使用的视图将失效.另请参见 com.sun.faces.numberOfViewsInSession与com.sun. faces.numberOfLogicalViews .

There is also a limit on the amount of views JSF will store in the session. When the limit is hit, then the least recently used view will be expired. See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews.

将状态保存方法设置为client时,javax.faces.ViewState隐藏的输入字段将包含整个序列化的视图状态,因此会话期满时最终用户将不会获得ViewExpiredException.但是,它仍然可能在群集环境下(错误:MAC未验证"是有症状的)和/或在配置的客户端状态上存在特定于实现的超时和/或在重新启动期间服务器重新生成AES密钥时发生,另请参见在设置了状态保存方法的群集环境中获取ViewExpiredException客户端和用户会话有效如何解决它.

With the state saving method set to client, the javax.faces.ViewState hidden input field contains instead the whole serialized view state, so the enduser won't get a ViewExpiredException when the session expires. It can however still happen on a cluster environment ("ERROR: MAC did not verify" is symptomatic) and/or when there's a implementation-specific timeout on the client side state configured and/or when server re-generates the AES key during restart, see also Getting ViewExpiredException in clustered environment while state saving method is set to client and user session is valid how to solve it.

不管解决方案如何,请确保您使用enableRestoreView11Compatibility.它根本不还原原始视图状态.它基本上从头开始重新创建视图和所有关联的视图作用域Bean,从而丢失所有原始数据(状态).由于应用程序将以一种混乱的方式运行(嘿,我的输入值在哪里?最好改用无状态视图或<o:enableRestorableView>,这样您就可以仅在特定视图而不是所有视图上对其进行管理.

Regardless of the solution, make sure you do not use enableRestoreView11Compatibility. it does not at all restore the original view state. It basically recreates the view and all associated view scoped beans from scratch and hereby thus losing all of original data (state). As the application will behave in a confusing way ("Hey, where are my input values..??"), this is very bad for user experience. Better use stateless views or <o:enableRestorableView> instead so you can manage it on a specific view only instead of on all views.

关于为什么 JSF需要保存视图状态,请转到以下答案:

As to the why JSF needs to save view state, head to this answer: Why JSF saves the state of UI components on server?

为了避免ViewExpiredException,例如当状态保存设置为server时,在注销后返回导航,仅在注销后重定向POST请求是不够的.您还需要指示浏览器缓存动态JSF页面,否则,当您在其中发送GET请求时,浏览器可能会从缓存中显示它们,而不是从服务器请求一个新的页面.通过后退按钮).

In order to avoid ViewExpiredException when e.g. navigating back after logout when the state saving is set to server, only redirecting the POST request after logout is not sufficient. You also need to instruct the browser to not cache the dynamic JSF pages, otherwise the browser may show them from the cache instead of requesting a fresh one from the server when you send a GET request on it (e.g. by back button).

缓存页面的javax.faces.ViewState隐藏字段可能包含视图状态ID值,该值在当前会话中不再有效.如果您正在(ab)使用POST(命令链接/按钮)而不是GET(常规链接/按钮)进行页面间导航,然后在缓存的页面上单击这样的命令链接/按钮,则依次失败,并显示ViewExpiredException.

The javax.faces.ViewState hidden field of the cached page may contain a view state ID value which is not valid anymore in the current session. If you're (ab)using POST (command links/buttons) instead of GET (regular links/buttons) for page-to-page navigation, and click such a command link/button on the cached page, then this will in turn fail with a ViewExpiredException.

要在JSF 2.0中注销后触发重定向,请在有问题的<navigation-case>中添加<redirect />,或者在outcome值中添加?faces-redirect=true.

To fire a redirect after logout in JSF 2.0, either add <redirect /> to the <navigation-case> in question (if any), or add ?faces-redirect=true to the outcome value.

<h:commandButton value="Logout" action="logout?faces-redirect=true" />

public String logout() {
    // ...
    return "index?faces-redirect=true";
}

要指示浏览器不要缓存动态JSF页面,请创建一个Filter,该映射到FacesServlet的servlet名称上,并添加所需的响应标头以禁用浏览器缓存.例如

To instruct the browser to not cache the dynamic JSF pages, create a Filter which is mapped on the servlet name of the FacesServlet and adds the needed response headers to disable the browser cache. E.g.

@WebFilter(servletNames={"Faces Servlet"}) // Must match <servlet-name> of your FacesServlet.
public class NoCacheFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if (!req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
            res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
            res.setDateHeader("Expires", 0); // Proxies.
        }

        chain.doFilter(request, response);
    }

    // ...
}

在页面刷新时避免ViewExpiredException

为了避免在状态保存设置为server时刷新当前页面时出现ViewExpiredException,您不仅需要确保仅通过GET(常规链接/按钮)执行页面到页面的导航),但您还需要确保您仅使用ajax提交表单.如果无论如何要同步提交表单(非ajax),则最好使视图变为无状态(请参见下一节),或者在POST之后发送重定向(请参见上一节).

Avoiding ViewExpiredException on page refresh

In order to avoid ViewExpiredException when refreshing the current page when the state saving is set to server, you not only need to make sure you are performing page-to-page navigation exclusively by GET (regular links/buttons), but you also need to make sure that you are exclusively using ajax to submit the forms. If you're submitting the form synchronously (non-ajax) anyway, then you'd best either make the view stateless (see later section), or to send a redirect after POST (see previous section).

在默认配置下,页面刷新上具有ViewExpiredException的情况很少见.仅当达到JSF将在会话中存储的视图数量限制时,才会发生这种情况.因此,只有在您手动将限制设置得太低或在后台"中不断创建新视图时(例如,在同一页面中实施不正确的Ajax轮询或实施不正确的404),才会发生这种情况错误页面出现在同一页面的损坏图像上).另请参见 com.sun.faces.numberOfViewsInSession与com.sun. faces.numberOfLogicalViews 了解有关该限制的详细信息.另一个原因是运行时类路径中的重复JSF库相互冲突. 我们的JSF Wiki页面中概述了正确安装JSF的步骤.

Having a ViewExpiredException on page refresh is in default configuration a very rare case. It can only happen when the limit on the amount of views JSF will store in the session is hit. So, it will only happen when you've manually set that limit way too low, or that you're continuously creating new views in the "background" (e.g. by a badly implemented ajax poll in the same page or by a badly implemented 404 error page on broken images of the same page). See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews for detail on that limit. Another cause is having duplicate JSF libraries in runtime classpath conflicting each other. The correct procedure to install JSF is outlined in our JSF wiki page.

如果要在任意页面上执行POST操作后处理不可避免的ViewExpiredException,而该页面已经在某个浏览器选项卡/窗口中打开,而您又在另一个选项卡/窗口中注销,则需要指定web.xml中的error-page转到您的会话已超时"页面.例如

When you want to handle an unavoidable ViewExpiredException after a POST action on an arbitrary page which was already opened in some browser tab/window while you're logged out in another tab/window, then you'd like to specify an error-page for that in web.xml which goes to a "Your session is timed out" page. E.g.

<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/WEB-INF/errorpages/expired.xhtml</location>
</error-page>

如有必要,请在错误页面中使用元刷新标题,以防您打算真正重定向进一步到主页或登录页面.

Use if necessary a meta refresh header in the error page in case you intend to actually redirect further to home or login page.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Session expired</title>
        <meta http-equiv="refresh" content="0;url=#{request.contextPath}/login.xhtml" />
    </head>
    <body>
        <h1>Session expired</h1>
        <h3>You will be redirected to login page</h3>
        <p><a href="#{request.contextPath}/login.xhtml">Click here if redirect didn't work or when you're impatient</a>.</p>
    </body>
</html>

(content中的0表示重定向之前的秒数,因此0表示立即重定向",您可以使用例如3让浏览器通过重定向等待3秒)

(the 0 in content represents the amount of seconds before redirect, 0 thus means "redirect immediately", you can use e.g. 3 to let the browser wait 3 seconds with the redirect)

请注意,在ajax请求期间处理异常需要特殊的ExceptionHandler.另请参见会话超时和对JSF/PrimeFaces ajax请求的ViewExpiredException处理.您可以在 OmniFaces FullAjaxExceptionHandler展示页面中找到一个实时示例(这也涵盖了非ajax请求) ).

Note that handling exceptions during ajax requests requires a special ExceptionHandler. See also Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request. You can find a live example at OmniFaces FullAjaxExceptionHandler showcase page (this also covers non-ajax requests).

还请注意,您的一般"错误页面应映射到500<error-code>上,而不是例如500<exception-type>上. java.lang.Exceptionjava.lang.Throwable,否则包装在ServletException中的所有异常(例如ViewExpiredException)仍将在常规错误页面中结束.另请参见 java.lang.Throwable中显示的ViewExpiredException web.xml中的错误页面.

Also note that your "general" error page should be mapped on <error-code> of 500 instead of an <exception-type> of e.g. java.lang.Exception or java.lang.Throwable, otherwise all exceptions wrapped in ServletException such as ViewExpiredException would still end up in the general error page. See also ViewExpiredException shown in java.lang.Throwable error-page in web.xml.

<error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/errorpages/general.xhtml</location>
</error-page>

无状态视图

一个完全不同的选择是在无状态模式下运行JSF视图.这样,将不会保存任何JSF状态,并且视图将永远不会过期,而只是在每个请求上从头开始重建.您可以通过将<f:view>transient属性设置为true来打开无状态视图:

Stateless views

A completely different alternative is to run JSF views in stateless mode. This way nothing of JSF state will be saved and the views will never expire, but just be rebuilt from scratch on every request. You can turn on stateless views by setting the transient attribute of <f:view> to true:

<f:view transient="true">

</f:view>

这样,javax.faces.ViewState隐藏字段将在Mojarra中获得固定值"stateless"(此时尚未检查MyFaces).请注意,此功能已在Mojarra 2.1.19和2.2.0中引入.并且在较早的版本中不可用.

This way the javax.faces.ViewState hidden field will get a fixed value of "stateless" in Mojarra (have not checked MyFaces at this point). Note that this feature was introduced in Mojarra 2.1.19 and 2.2.0 and is not available in older versions.

结果是您不能再使用视图作用域的bean.现在,它们的行为类似于请求范围的Bean.缺点之一是您必须通过摆弄隐藏的输入和/或宽松的请求参数来自己跟踪状态.主要是那些受ajax事件控制的具有renderedreadonlydisabled属性的输入字段的表单.

The consequence is that you cannot use view scoped beans anymore. They will now behave like request scoped beans. One of the disadvantages is that you have to track the state yourself by fiddling with hidden inputs and/or loose request parameters. Mainly those forms with input fields with rendered, readonly or disabled attributes which are controlled by ajax events will be affected.

请注意,<f:view>不一定在整个视图中都是唯一的和/或仅驻留在主模板中.重新声明并将其嵌套在模板客户端中也是完全合法的.然后,它基本上扩展"了父<f:view>.例如.在主模板中:

Note that the <f:view> does not necessarily need to be unique throughout the view and/or reside in the master template only. It's also completely legit to redeclare and nest it in a template client. It basically "extends" the parent <f:view> then. E.g. in master template:

<f:view contentType="text/html">
    <ui:insert name="content" />
</f:view>

以及在模板客户端中:

<ui:define name="content">
    <f:view transient="true">
        <h:form>...</h:form>
    </f:view>
</f:view>

您甚至可以将<f:view>包裹在<c:if>中,使其成为有条件的.请注意,它不仅适用于 entire 视图,而且不仅适用于嵌套内容,例如上例中的<h:form>.

You can even wrap the <f:view> in a <c:if> to make it conditional. Note that it would apply on the entire view, not only on the nested contents, such as the <h:form> in above example.

  • ViewExpiredException shown in java.lang.Throwable error-page in web.xml
  • Check if session exists JSF
  • Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request

无关与具体问题无关,使用HTTP POST进行纯页面到页面导航对用户/SEO不太友好.在JSF 2.0中,对于普通香草的逐页导航,您真的应该更喜欢<h:link><h:button>而不是<h:commandXxx>.

Unrelated to the concrete problem, using HTTP POST for pure page-to-page navigation isn't very user/SEO friendly. In JSF 2.0 you should really prefer <h:link> or <h:button> over the <h:commandXxx> ones for plain vanilla page-to-page navigation.

因此而不是例如

<h:form id="menu">
    <h:commandLink value="Foo" action="foo?faces-redirect=true" />
    <h:commandLink value="Bar" action="bar?faces-redirect=true" />
    <h:commandLink value="Baz" action="baz?faces-redirect=true" />
</h:form>

做得更好

<h:link value="Foo" outcome="foo" />
<h:link value="Bar" outcome="bar" />
<h:link value="Baz" outcome="baz" />

另请参见

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆