Set custom filter on Tomcat 8 using web.xml

最后都变了- 提交于 2020-12-15 05:42:05

问题


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);
  }
}

回答1:


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>


来源:https://stackoverflow.com/questions/56375669/set-custom-filter-on-tomcat-8-using-web-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!