title: Redirecting a web client from a servlet-filter (client-server connection via AJAX)
body: <p>I'm doing a web with JAASRealm authentication (in tomcat 7).
  This is a filter for the servlets:</p>
  
  <pre><code>private String loginPage = "welcome.jsp";
  
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
          FilterChain filterChain) throws IOException, ServletException {
  
      if ((request instanceof HttpServletRequest) &amp;&amp; (response instanceof HttpServletResponse)) {
          HttpServletRequest httpServletRequest = (HttpServletRequest) request;
          HttpServletResponse httpServletResponse = (HttpServletResponse) response;
          if (httpServletRequest.getUserPrincipal() == null) {
              // User is not logged in, redirect to login page.
              httpServletRequest.setAttribute("from", httpServletRequest.getRequestURI());
              httpServletResponse.sendRedirect(loginPage);
          }
          else {
              filterChain.doFilter(request, response);
          }
      }
  }
  </code></pre>
  
  <p>And I have declared it in web.xml</p>
  
  <pre><code>&lt;filter&gt;
      &lt;filter-name&gt;login-filter&lt;/filter-name&gt;
      &lt;filter-class&gt;LoginFilter&lt;/filter-class&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;login-filter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/sampleServlet&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  </code></pre>
  
  <p>My problem is when I'm not authenticated and I call the servlet via AJAX, this line of filter doesn't work</p>
  
  <pre><code>httpServletResponse.sendRedirect(loginPage);
  </code></pre>
  
  <p>So, I haven't receive any data and I'm not redirected to the loggin page. What can I do in this case?</p>