呈现页面之前的验证 [英] validation before rendering page
问题描述
我是JSF的新手,并使用JSF2来构建一个具有多个页面的webapp.我正在使用一个会话范围的Bean来保留通过浏览不同页面而设置的一些参数.
I'm new to JSF and using JSF2 to build a webapp which has several pages. I'm using a session scoped bean to keep some parameters that were set by going through the different pages.
当会话超时(或我重新部署应用程序)并且转到特定页面时,该页面将无法正确呈现,因为会话中缺少一些数据.此时,我希望显示主页.
When the session times out (or I redeploy the app) and I go to a specific page then this page is not able to render correctly because some data is missing from the session. At this point I want the home page to be shown.
我想对所有页面使用此机制.因此,总的来说,我想在呈现页面之前进行一些验证,如果验证失败,则将用户定向到主页.
I want to use this mechanism for all pages. So in general I want to do some validation before rendering a page and direct the user to the home page if the validation fails.
我应该如何处理?
推荐答案
在这种特殊情况下,我将使用简单的过滤器挂接到JSF请求并检查会话中托管bean的存在.下面的示例假定以下条件:
In this particular case I'd use a simple filter which hooks on JSF requests and checks the presence of the managed bean in the session. The below example assumes the following:
-
FacesServlet
在web.xml
中定义为<servlet-name>facesServlet</servlet-name>
- 您的会话作用域bean的受管理bean名称为
yourSessionBean
. - 您的主页位于
home.xhtml
FacesServlet
is definied inweb.xml
as<servlet-name>facesServlet</servlet-name>
- Your session scoped bean has a managed bean name of
yourSessionBean
. - Your home page is located at
home.xhtml
@WebFilter(servletName="facesServlet")
public class FacesSessionFilter implements Filter {
@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);
if (!request.getRequestURI().endsWith("/home.xhtml") && (session == null || session.getAttribute("yourSessionBean") == null)) {
response.sendRedirect(request.getContextPath() + "/home.xhtml"); // Redirect to home page.
} else {
chain.doFilter(req, res); // Bean is present in session, so just continue request.
}
}
// Add/generate init() and destroy() with empty bodies.
}
或者,如果您想做更多JSF式的操作,请在主模板中添加<f:event type="preRenderView">
.
Or if you want to do it more JSF-ish, add a <f:event type="preRenderView">
to the master template.
<f:metadata>
<f:event type="preRenderView" listener="#{someBean.preRenderView}" />
</f:metadata>
使用
@ManagedProperty(value="#{yourSessionBean}")
private YourSessionBean yourSessionBean;
public void preRenderView() {
if (yourSessionBean.isEmpty()) {
yourSessionBean.addPage("home");
FacesContext.getCurrentInstance().getExternalContext().redirect("/home.xhtml");
}
}
这篇关于呈现页面之前的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!