Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6879557
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T04:51:41+00:00 2026-05-27T04:51:41+00:00

I am working on a JSF 2.0 website. The website has two kind of

  • 0

I am working on a JSF 2.0 website. The website has two kind of users(public and registered). Now I want to know that how can I create session for both kind of users? For registered users, when my user is login then there should be session for it, and when session expires then I redirect it to page that your session has expired. For public users there should be no session at all. Means there is no session time out for my public users and they never have messages that your session has expired. How can I implement this behavior in JSF 2.0.

Can I use filter for it or there is better approach for it? I also read that JSF automatically creates session using managed beans. Can I use these sessions for my task?

Edit:

I tell you what i did so you people better guide me in this scenerio

What i did i put a filter in my web app like this

<filter>
    <filter-name>SessionTimeoutFilter</filter-name>
    <filter-class>util.SessionTimeoutFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SessionTimeoutFilter</filter-name>
    <url-pattern>*.xhtml</url-pattern>
</filter-mapping>

Here is my Filter code

public class SessionTimeoutFilter implements Filter {

    // This should be your default Home or Login page
    // "login.seam" if you use Jboss Seam otherwise "login.jsf"   
    // "login.xhtml" or whatever
    private String timeoutPage = "faces/SessionExpire.xhtml";
    private String welcomePage = "faces/index.xhtml";
    public static Boolean expirePage = false;
    private FilterConfig fc;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        this.fc = filterConfig;

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,   FilterChain filterChain)
        throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        HttpSession session = httpServletRequest.getSession();

        /**
         * The session objects have a built-in data structure (a hash table) in which you can store
         * any number of keys and associated values. You use session.getAttribute("key") to look up
         * a previously stored value. The return type is Object, so you must do a typecast to
         * whatever more specific type of data was associated with that attribute name in the session.
         * The return value is null if there is no such attribute, so you need to check for null
         * before calling methods on objects associated with sessions.
         *
         * Note:
         *     JSF session scoped managed beans are under the covers stored as a HttpSession
         *     attribute with the managed bean name as key.
         */
        Login login = (Login)session.getAttribute("login");

        if (login == null) {  // No such object already in session

            filterChain.doFilter(request, response);

        } else {

            /**
             * If you use a RequestDispatcher, the target servlet/JSP receives the same
             * request/response objects as the original servlet/JSP. Therefore, you can pass
             * data between them using request.setAttribute(). With a sendRedirect(), it is a
             * new request from the client, and the only way to pass data is through the session or
             * with web parameters (url?name=value).
             */
            filterChain.doFilter(request, response);

        }

        System.out.println();

    } //end of doFilter()

    @Override
    public void destroy() {

    } //end of destroy()

Now what happen that if you first time enter url of my site then this filter invoke. It gets

Login login = (Login)session.getAttribute("login");

null. So it simply move to my index.xhtml page. Now my index.html page constructor invokes. Here is my code

@ManagedBean
//////@RequestScoped
@SessionScoped
public class Login implements Serializable {

    //Constructor
    public Login() {

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();

        //getSession(false), which returns null if no session already exists for the current client.
        HttpSession session =(HttpSession)externalContext.getSession(false);

        if (session == null) {

            System.out.println();

        } else {

            session.setAttribute("logedin", 0);     //public user
            session.setMaxInactiveInterval(-1);     // no session time out

            Enumeration e = session.getAttributeNames();

            while (e.hasMoreElements()) {

                /**
                 * Here you also get "login" attr. Because when managed bean create the
                 * session, it sets you managedBean name in the session attribute.
                 */
                String attr = (String)e.nextElement();
                System.err.println("attr  = "+ attr);
                Object value = session.getAttribute(attr);
                System.err.println("value = "+ value);

            } //end of while

        }

    }//end of constructor

} //end of class Login

when first time user come to my site then it is not login so i set logedin session attribute 0. Now suppose user enter credentials and press log in button. First my filter is invoke but this time it will get login attribute and comes to my doFilter() else check and then come to My validUser() method. Here is my code

public String validUser() throws Exception {

    ArrayList2d<Object> mainarray = new ArrayList2d<Object>();
    mainarray.addRow();
    mainarray.add(userName);
    mainarray.add(password);

    busBeans.usermanagement.users um = new busBeans.usermanagement.users();
    ArrayList retrieveList = um.getValidUser(mainarray);    //database check of user existence

    if (Integer.parseInt(retrieveList.get(0).toString()) == 0) {

        ArrayList str = (ArrayList) retrieveList.get(1);

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();

        //getSession(false), which returns null if no session already exists for the current client.
        HttpSession session =(HttpSession)externalContext.getSession(false);

        if (session == null) {

            System.out.println();

        } else {

            Enumeration e = session.getAttributeNames();

            while (e.hasMoreElements()) {

                String attr = (String)e.nextElement();
                System.err.println("attr  = "+ attr);
                Object value = session.getAttribute(attr);
                System.err.println("value = "+ value);

            } //end of while

        }

        logedin=true;
        session.setAttribute("logedin", 1);
        session.setAttribute("firstLastName", str.get(7).toString());
        session.setAttribute("getusercredentials", str);
        session.setAttribute("sessionUserId", str.get(0).toString());
        session.setAttribute("sessionRoleId",str.get(1).toString());
        firstLastName = session.getAttribute("firstLastName").toString();
        session.setMaxInactiveInterval(60);  //1 min
        ConnectionUtil.setRgihts(Integer.parseInt(str.get(0).toString()) , Integer.parseInt(str.get(1).toString()) ,Integer.parseInt(str.get(5).toString()));
        checkRgihts();
    }

} //end of validUser()

Now i want to ask one thing. I set sessionTimeout using setMaxInterval. Is it ok or it is better to do in web.xml? Now whne timeOut expires then filter doesn’t invoke. But suppose that I also attach HttpSessionListener. Then on session time Out its destroy method invoke. I can invalidate session here. Like this.

public class MySessionListener implements HttpSessionListener {

    // Constructor
    public MySessionListener() {

    } //end of constructor

    @Override
    public void sessionCreated(HttpSessionEvent event) {

        System.out.println("Current Session created : " + event.getSession().getCreationTime());
        System.out.println();


    } //end of sessionCreated()

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {

        // get the destroying session...
        HttpSession session = event.getSession();

        if (session != null) {

            session.invalidate();

        }

        System.out.println();

    } //end of sessionDestroyed()

} //end of class MySessionListener

But on session expiration i also want to redirect user to redirecr Page if this is a registered user. IF this is a public user i don’t want to redirect it although session has expired. I can check in the destroy method by getting attribute logedin that it is a public user or registered user. But then how can i redirect for registered user or do nothing for public user.

If somehow my filter invoke on session time out and some how i check that if this is a registered user by getting logedin attribute 1 and session time out has expired, because for public user i set timeout -1, then redirect the user, using RequestDispatcher otherwoise do filterChain.doFilter(request, response);.

So this is the scenerio that i implemented. I don’t know whether my approaches are right or not ? I don’t know what security issues i will face by this approach. So that’s it.. Now you people guide me what should i do…..

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T04:51:42+00:00Added an answer on May 27, 2026 at 4:51 am

    I understand what your goal is, but I don’t think that not having a Session for unauthenticated users is particularly the best approach.

    Consider an unauthenticated user navigating through a Primefaces wizard as he provides information to sign up for an account, (Eg. Pick Username, Provide Password, Choose Security Questions, etc…)

    You are not going to want to persist this user information until it all has been collected and validated, because perhaps the user has a change of heart and decides not to sign up? Now you have an incomplete user record in your database that needs to be cleaned.

    The answer is that you need to store this information in a ViewScoped bean or in session until the unauthenticated user confirms the account creation, where it can finally be persisted.

    What I feel the best approach would be is for you to give a User a unique Role with one role being Unauthenticated. Using components like Spring Security 3 or even Seam you should be able to control page Authorization through the Role of the User in Session.

    For instance, you can prevent unauthenticated users from entering pages in ../app/* or normal users from accessing pages in ../admin/*

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Working on a website that has Employee and Branch entities, using a database table
I am working on a JSF application that was written overseas and it has
I am using JSF with richfaces3.3.3, other jsf capabilities working but i don't know
I am working on a JSF page which has a dropdown based on List<SelectItem>
I want to create User Interface in JSF. Is there any tool apart from
I'm the beginner with JSF. As I know, to start working with JSF I
I'm working on a JSF 2 web application. If I define a facelet that
I am working with a JSF application that posts on every mouse click, so
I have a JSF/ICEFaces application that was working fine but all of the sudden
I'm currently working on a web app that makes heavy use of JSF and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.