简体   繁体   English

Xhtml页面和HttpSession测试,没有jstl吗?

[英]Xhtml pages and HttpSession test , no jstl?

I have a dynamic web application in Java EE with JSF, Facelets, Richfaces. 我在Java EE中有一个带有JSF,Facelets,Richfaces的动态Web应用程序。 My pages are all xhtml pages. 我的页面都是xhtml页面。 So JSTL isn't working in it. 因此,JSTL无法使用。 For my account pages and all other private pages to be reachable, I want to test if the user got connected, so if the attribute session in HttpSession is not null. 为了使我的帐户页面和所有其他私有页面都可以访问,我想测试用户是否已连接,因此,如果HttpSession的属性会话不为null。 If it's null, the user gets redirected in the welcome page. 如果为null,则会在欢迎页面中重定向用户。

I tried in my xhtml page : 我在xhtml页面中尝试过:

<jstl:if test="${sessionScope['session']==null}">
 <jstl redirect...>
</jstl:if>-->

but as it's not jsp page it won't work. 但由于它不是jsp页面,因此无法使用。 So where am I supposed to test if the session is not null to allow the user to see his private pages ? 因此,我应该在哪里测试会话是否不为null以允许用户查看其私人页面? in a central managed bean ? 在中央托管bean中?

The normal place for this is a Filter . 正常的位置是Filter

Create a class which implements javax.servlet.Filter and write the following logic in the doFilter() method: 创建一个implements javax.servlet.Filter的类,并在doFilter()方法中编写以下逻辑:

if (((HttpServletRequest) request).getSession().getAttribute("user") == null) {
    // Not logged in, so redirect request to login page.
    ((HttpServletResponse) response).sendRedirect("/login.jsf");
} else {
    // Logged in, so just continue request.
    chain.doFilter(request, response);
}

Map this filter in web.xml on an url-pattern of something like /private/* , /secured/* , /restricted/* , etc. 将这个过滤器映射到类似/private/*/secured/*/restricted/*等的url-patternweb.xml

<filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.example.LoginFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>loginFilter</filter-name>
    <url-pattern>/private/*</url-pattern>
</filter-mapping>

If you have the private pages in the /private folder then this filter will be invoked and handle the presence of the logged-in user in the session accordingly. 如果/private文件夹中有私人页面,则将调用此过滤器并相应地处理会话中已登录用户的状态。

Note that I renamed attribute name session to user since that makes much more sense. 请注意,我将属性名称session重命名为user因为这更有意义。 The HttpSession itself is namely already the session. HttpSession本身即已是会话。 It would otherise been too ambiguous and confusing for other developers checking/maintaining your code. 对于其他开发人员检查/维护您的代码,这将变得过于模棱两可且令人困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM