简体   繁体   中英

Set custom filter on Tomcat 8 using web.xml

I want to enable CORS Tomcat 8 using this method (custom filter) Tomcat CORS filter

I'm confused on step making custom filter to be called in web.xml.

How to set the .java file? Where is the directory of this file (SimpleCORSFilter)?

public class SimpleCORSFilter implements Filter {

  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletResponse response = (HttpServletResponse) res;
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
      chain.doFilter(req, res);
  }
}

Define filter as example connected to URL:

 <filter> <filter-name>cors</filter-name> <filter-class>com.robin.filters.SimpleCORSFilter</filter-class> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 

Define filter as example connected to servlet:

 <filter> <filter-name>MyFilter</filter-name> <display-name>MyFilter</display-name> <filter-class>com.xxx.yyy.zzz.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <servlet-name>MyAction</servlet-name> </filter-mapping> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM