1. 程式人生 > >java跨域過濾器配置

java跨域過濾器配置

java程式碼

public class SimpleCorsFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(SimpleCorsFilter.class);
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;
		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", "Content-Type,x-requested-with, authorization");
		response.setHeader("Access-Control-Allow-Credentials", "true");

		logger.debug("Receive request method = {}, url = {}", request.getMethod(), request.getRequestURI());
		if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
			logger.debug("處理請求方法:-------- {} -------", "OPTIONS");
			response.setStatus(HttpServletResponse.SC_OK);
		} else {
			chain.doFilter(req, res);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}

web.xml配置

 

<filter>
    <filter-name>simpleCorsFilter</filter-name>
    <filter-class>com.hollysmart.admin.modules.sys.filter.SimpleCorsFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>simpleCorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>