package com.cloudtech.web.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author wude
* @version 1.0.0
* @description
* @date 2018-08-17 14:38
*/
public class SimpleCORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type");
httpServletResponse.addHeader("Access-Control-Max-Age", "1800");//30 min
filterChain.doFilter(servletRequest, httpServletResponse);
}
@Override
public void destroy() {
}
}
web.xml
<!-- cors解决跨域访问问题 -->
<filter>
<filter-name>cors</filter-name>
<filter-class>com.cloudtech.web.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>