问题
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