Reputation: 1054
I have a simple HttpServlet Filter in Tomcat 8 that I want to use on every request, and then proceed to the other servlets. But the filter is not being executed at all. Here is the web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>requestFilter</filter-name>
<filter-class>controller.RequestsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestFilter</filter-name>
<servlet-name>index</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>index</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>
and here is the filter:
@WebFilter
public class RequestsFilter extends HttpServlet implements Filter {
static Logger log = Logger.getLogger("RequestFilter");
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
req.setAttribute("key", "some random string");
log.warning("**RequestFilter**");
filterChain.doFilter(req, resp);
}
}
Would appreciate any help, and thanks.
Upvotes: 1
Views: 314
Reputation: 8495
This is NOT a filter.
You are mixing up servlet and filters. Filter and Servlet are completely two different things.
public class RequestsFilter extends HttpServlet implements Filter {
I can see some issues in your web.xml as well. <servlet-name>
should not be there in <filter-mapping>
<servlet-name>index</servlet-name>
You can find a simple yet clean example here.
Upvotes: 2