title: Servlet filter with JSF
body: <p>I tried to configure Servlet filter with JSF. I get lot of problems here I am using PrimeFaces also.</p>
  
  <p>Here is my web.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"&gt;
    &lt;display-name&gt;JsfEaxmples&lt;/display-name&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;javax.faces.STATE_SAVING_METHOD&lt;/param-name&gt;
      &lt;param-value&gt;server&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;javax.faces.DEFAULT_SUFFIX&lt;/param-name&gt;
      &lt;param-value&gt;.xhtml&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;javax.faces.PROJECT_STAGE&lt;/param-name&gt;
      &lt;param-value&gt;Development&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;javax.faces.FACELETS_REFRESH_PERIOD&lt;/param-name&gt;
      &lt;param-value&gt;1&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;javax.faces.FACELETS_SKIP_COMMENTS&lt;/param-name&gt;
      &lt;param-value&gt;true&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;javax.faces.SEPARATOR_CHAR&lt;/param-name&gt;
      &lt;param-value&gt;-&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;org.richfaces.skin&lt;/param-name&gt;
      &lt;param-value&gt;classic&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;facelets.BUILD_BEFORE_RESTORE&lt;/param-name&gt;
      &lt;param-value&gt;true&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;facelets.RECREATE_VALUE_EXPRESSION_ON_BUILD_BEFORE_RESTORE&lt;/param-name&gt;
      &lt;param-value&gt;true&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;servlet&gt;
      &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
      &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
      &lt;url-pattern&gt;*.xhtml&lt;/url-pattern&gt;
  
    &lt;/servlet-mapping&gt;
    &lt;context-param&gt;
      &lt;param-name&gt;javax.servlet.jsp.jstl.fmt.localizationContext&lt;/param-name&gt;
      &lt;param-value&gt;resources.application&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;listener&gt;
      &lt;listener-class&gt;com.sun.faces.config.ConfigureListener&lt;/listener-class&gt;
    &lt;/listener&gt;
    &lt;filter&gt;
    &lt;filter-name&gt;sessionfilter&lt;/filter-name&gt;
    &lt;filter-class&gt;com.invoice.sessionfilter&lt;/filter-class&gt;
  
    &lt;/filter&gt;
    &lt;filter-mapping&gt;
    &lt;filter-name&gt;sessionfilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  
    &lt;/filter-mapping&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <p>First I used filter like this <code>&lt;url-pattern&gt;jsf invoice system/*&lt;/url-pattern&gt;</code>this totally didn't work so I changed to <code>&lt;url-pattern&gt;/*&lt;/url-pattern&gt;</code>this one responds but give lot of problems in my filtering
  I check these following process with filter</p>
  
  <ol>
  <li>If session doesn't exists user should be redirected to login page</li>
  <li>if session exists and if user goes to login page he should not be redirected  </li>
  </ol>
  
  <p>more over after adding filter PrimeFaces components appearance changes. After adding filter, it's not getting navigated properly.</p>
  
  <p>Here is my filter code.</p>
  
  <pre><code>package com.invoice;
  
  import java.io.IOException;
  
  import javax.servlet.Filter;
  import javax.servlet.FilterChain;
  import javax.servlet.FilterConfig;
  import javax.servlet.ServletException;
  import javax.servlet.ServletRequest;
  import javax.servlet.ServletResponse;
  import javax.servlet.annotation.WebFilter;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.HttpSession;
  
  public class sessionfilter implements Filter {
  
      String uname;
  
      /**
       * Default constructor.
       */
      public sessionfilter() {
          // TODO Auto-generated constructor stub
      }
  
      /**
       * @see Filter#destroy()
       */
      public void destroy() {
          // TODO Auto-generated method stub
      }
  
      /**
       * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
       */
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
          // place your code here
  
          // pass the request along the filter chain
          HttpServletRequest req = (HttpServletRequest) request;
          HttpServletResponse resp = (HttpServletResponse) response;
          String pagerequested = req.getRequestURL().toString();
          HttpSession ses = req.getSession(true);
          //uname=(String)ses.getAttribute("uname");//null pointer exception
          if (pagerequested.contains("Login.xhtml") &amp;&amp; uname == null)// if user logs in to this for first time
          {
  
              chain.doFilter(request, response);
  
          } else if (uname != null &amp;&amp; pagerequested.contains("Login.xhtml")) { // if session exists and user tries to go to login page he should be redirected
  
              resp.sendRedirect("invoiceinfo.xhtml");
  
          } else if (uname == null &amp;&amp; !pagerequested.contains("Login.xhtml")) {
  
              try {
                  uname = (String) ses.getAttribute("uname");
                  chain.doFilter(request, response);
  
              } catch (Exception e) {
                  resp.sendRedirect("Login.xhtml");
              }
          }
      }
  
      /**
       * @see Filter#init(FilterConfig)
       */
      public void init(FilterConfig fConfig) throws ServletException {
          // TODO Auto-generated method stub
      }
  
  }
  </code></pre>
  
  <p>Here is my login bean with sessionn scoped i dont use annotation here</p>
  
  <pre><code>package com.invoice;
  
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.ResultSet;
  import java.sql.Statement;
  
  import javax.faces.bean.SessionScoped;
  import javax.faces.context.FacesContext;
  import javax.servlet.http.HttpSession;
  
  @SessionScoped
  public class login {
  
      String username, userpassword, errormess, navipg;
  
      public String getNavipg() {
          return navipg;
      }
  
      public void setNavipg(String navipg) {
          this.navipg = navipg;
      }
  
      public String getErrormess() {
          return errormess;
      }
  
      public void setErrormess(String errormess) {
          this.errormess = errormess;
      }
  
      public String getUsername() {
          return username;
      }
  
      public void setUsername(String username) {
          this.username = username;
      }
  
      public String getUserpassword() {
          return userpassword;
      }
  
      public void setUserpassword(String userpassword) {
          this.userpassword = userpassword;
      }
  
      public String navigate() {
          try {
              Class.forName("oracle.jdbc.driver.OracleDriver");
              Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "invoice", "google");
              Statement stmt = con.createStatement();
              ResultSet rs = stmt.executeQuery("select username,password from usertable where username='" + username + "' and password='" + userpassword + "' ");
              if (rs.next()) {
                  setErrormess("");
                  FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("uname", this.username);
                  navipg = "invoiceinfo";
              } else {
                  setErrormess("Invalid Login credentials");
                  username = "";
                  navipg = "Login";
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
  
          return navipg;
      }
  
      public String logout() {
          FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
          return "Login";
      }
  }
  </code></pre>
  
  <p>My login page is</p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  
  &lt;html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:p="http://primefaces.org/ui"&gt;
  
      &lt;h:head&gt;
          &lt;style type="text/css"&gt;
              .ui-panelgrid tr,
              .ui-panelgrid td {
                  border: none;
              }
          &lt;/style&gt;
      &lt;/h:head&gt;
  
      &lt;h:body&gt;
          &lt;h:form&gt;
              &lt;p:panelGrid columns="3" id="pnl" border= "0"&gt;
                  &lt;f:facet name="header"&gt;&lt;p:graphicImage value="login.jpg"/&gt;&lt;/f:facet&gt;
                  &lt;h:outputText value="Username"/&gt;
  
                  &lt;p:inputText id="uname" value="#{login.username}" required="true" label="username"/&gt;
                  &lt;p:message for="uname"/&gt;
  
                  &lt;h:outputText value="Password"/&gt;
                  &lt;p:password id="pass" value="#{login.userpassword}" required="true" label="password"/&gt;
                  &lt;p:message for="pass"/&gt;
  
                  &lt;p:commandButton value="Login" action="#{login.navigate}" ajax="false"/&gt;
                  &lt;p:button value="Reset" /&gt;
              &lt;/p:panelGrid&gt;
  
              &lt;h1&gt;&lt;h:outputText value="#{login.errormess}"/&gt;&lt;/h1&gt;
          &lt;/h:form&gt;
      &lt;/h:body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>I'm totally stuck here and not getting idea how to proceed with filter.</p>