I’m doing a web with JAASRealm authentication (in tomcat 7).
This is a filter for the servlets:
private String loginPage = "welcome.jsp";
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if ((request instanceof HttpServletRequest) && (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);
}
}
}
And I have declared it in web.xml
<filter>
<filter-name>login-filter</filter-name>
<filter-class>LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>login-filter</filter-name>
<url-pattern>/sampleServlet</url-pattern>
</filter-mapping>
My problem is when I’m not authenticated and I call the servlet via AJAX, this line of filter doesn’t work
httpServletResponse.sendRedirect(loginPage);
So, I haven’t receive any data and I’m not redirected to the loggin page. What can I do in this case?
Here is how I send re-directs when Filtering AJAX requests…
AJAX Code (jQuery)
Relevant Filter Code