1

I want to get redirecting to start page when session is not opened or closed. I added Servlet Filter but it's not working.

My SessionFilter class:

public class SessionFilter implements Filter {

    private ArrayList<String> urlList;

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String url = request.getServletPath();
        HttpSession session = request.getSession(false);

        if (new Bean().getLoggedIn() || urlList.contains(url) || session != null){
            chain.doFilter(req, resp);
        }
        else{
            response.sendRedirect("index.jsf");
        }
    }

    public void init(FilterConfig config) throws ServletException {
        String urls = config.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");

        urlList = new ArrayList<String>();

        while (token.hasMoreTokens()) {
            urlList.add(token.nextToken());

        }
    }

    public void destroy() {
    }

}


My web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">
    <filter>
        <filter-name>SessionFilter</filter-name>
        <filter-class>com.tsystems.demail.SessionFilter</filter-class>
        <init-param>
            <param-name>avoid-urls</param-name>
            <param-value>/index.jsf, /registration.jsf</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>SessionFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsf</welcome-file>
    </welcome-file-list>
</web-app>

When I login new Bean().getLoggedIn() is true. When logout - false. How to change my filter? Where I have error?

informatik01
  • 16,038
  • 10
  • 74
  • 104
rubaka
  • 47
  • 1
  • 5
  • 10
  • 3
    What's `Bean`? Do you mean to create a new one *every* time? – Dave Newton Jul 02 '13 at 13:29
  • 1
    "but it's not working" How does it not work, it doesn't redirect at all, it redirects to the wrong page, you get an HTTP 500, nothing happens, what? Does the code in the else block execute at all, as determined by a debugger? More detail please, thanks. – Keith Jul 02 '13 at 13:29
  • @DaveNewton my Bean class: http://pastebin.com/EKU1d0EY – rubaka Jul 02 '13 at 13:33
  • @Keith I not having redirecting, when session closed or not opened. – rubaka Jul 02 '13 at 13:33
  • Check if the session is null, and check your urlList/url value, I think it will not work like you intend – Teg Jul 02 '13 at 13:34
  • @Teg I was checking. I have redirecting on some pages, when I logged, and i don't have, when session is closed. – rubaka Jul 02 '13 at 13:36
  • What Dave meant is, why in earth are you manually creating the bean (thus, with all its properties set to default!) using the `new` operator instead of grabbing and using the one created and managed by JSF itself from the HTTP session? – BalusC Jul 02 '13 at 13:59
  • @BalusC My boner :[. I change it, but now I have one more bug. Pages which not include in "avoid-urls" list not redirecting by filter. In debug mode I have not null session. When I remove "session!=null" parameter All pages redirecting to index.jsf. How to fix It? – rubaka Jul 02 '13 at 14:21
  • You should not be interested in whether the HTTP session has been created, but whether the user is logged in or not. – BalusC Jul 02 '13 at 14:23
  • @BalusC I change some code. Now Filter redirecting all pages (include avoid-urls) http://oi44.tinypic.com/zvtnxu.jpg UPDATE: redirecting avoid-urls. Login is success. – rubaka Jul 02 '13 at 14:44
  • @BalusC ... and one more bug. When I log out, my css style is not loading o_o – rubaka Jul 02 '13 at 14:49
  • That filter indeed redirects all browser's requests for CSS, JS and image resources to the index page when user is not logged in. The browser basically ends up retrieving the index page everytime instead of the requested CSS, JS and image files. – BalusC Jul 02 '13 at 14:55
  • Related: http://stackoverflow.com/questions/14526574/jsf-page-style-missing-when-using-login-filter/ – BalusC Jul 02 '13 at 14:57
  • @BalusC It's not solve my problem. Now filter is working, but CSS is not loading :( – rubaka Jul 02 '13 at 16:25

2 Answers2

1

I think you should try with:

 response.sendRedirect(request.getContextPath() + "/index.jsf");

Instead of :

response.sendRedirect("index.jsf"); 

But please Check the example below :

I assume in a login method, I put the current user in the session, so that i can get the not null object when the user is connected!

Method Login :

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

 Map<String, Object> sessionMap = externalContext.getSessionMap();

 sessionMap.put("User", wantConnect);   

Now, if an user tries access some pages with a url-pattern member such as http://www.domain.com/member/...., the below filter is called.

@WebFilter("/member/*")  
public class RequestInterceptor implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws ServletException, IOException {

      HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();

        if (session == null || session.getAttribute("User") == null) {
            response.sendRedirect(request.getContextPath() + "/index.xhtml"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }




}

@Override
public void destroy() {
    // Cleanup global variables if necessary.
}

}

Here my web.xml

<filter>
    <description>Requires user to log in as a member</description>
    <filter-name>RequestInterceptor</filter-name>
    <filter-class>fr.atoswg.peu.security.RequestInterceptor</filter-class>
</filter>
<filter-mapping>
    <filter-name>RequestInterceptor</filter-name>
    <url-pattern>/member/*</url-pattern>
</filter-mapping>

Hope it's help :) !

Rollyng
  • 1,387
  • 2
  • 12
  • 18
0

Note that response.sendRedirect("index.jsf")

takes a relative path as its argument. So, assuming that index.jsf is in the root of your web app, you probably want to use the value "/index.jsf" (starts with forward slash) to handle redirects at all levels. If not, a url like this:

/folder1/folder2/somePage.jsf

will be redirected to

/folder1/folder2/index.jsf

instead of

 /index.jsf
Keith
  • 4,144
  • 1
  • 19
  • 14