欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java使用filter设置跨域访问

程序员文章站 2022-07-06 15:41:24
...
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthorityFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		HttpServletResponse nHttpServletResponse = (HttpServletResponse) response;

		HttpServletRequest nHttpServletRequest = (HttpServletRequest) request;

		String nAppKey = nHttpServletRequest.getHeader("Accept-Key");
		if (nAppKey == null || "".equals(nAppKey)) {
			nHttpServletResponse.setStatus(403);
			return;
		} else {
			// 存在则验证准确性
//			if (!nAppKey.toString().equals(XSetting.ZTOKEN_KEY)) {
//				nHttpServletResponse.setStatus(403);
//				return;
//			}
		}

		nHttpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
		nHttpServletResponse.setHeader("Access-Control-Allow-Headers","Accept-Key");
		chain.doFilter(request, nHttpServletResponse);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
相关标签: java filter