• 使用filter解决跨域


    在web.xml配置拦截器

    	<filter>
    		<filter-name>servletFilterTest</filter-name>
    		<filter-class>cn.test.intercepter.ServletFilterTest</filter-class>
    	</filter>
    	<filter-mapping>
    		<filter-name>servletFilterTest</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    

    过滤器代码:

    import org.springframework.web.bind.annotation.RequestMethod;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class ServletFilterTest implements Filter {
    
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            httpServletRequest.getSession();
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpResponse.setHeader("Access-Control-Allow-Methods", "*");
            httpResponse.setHeader("Access-Control-Max-Age", "3600");
            httpResponse.setHeader("Access-Control-Allow-Headers",
                    "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Content-type", "application/json");
            httpResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
    
            if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
                return ;
            }
            filterChain.doFilter(httpServletRequest, httpResponse);
    
        }
    
        @Override
        public void destroy() {
    
        }
    }
    
    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    【NumPy】理清Reshape和Transpose
    【NumPy】What does axis/axes mean in Numpy
    【Git】测试部Git使用规范
    NCNN性能测试笔记
    MNN性能测试笔记
    Android Studio 查看SQLite数据库存储位置及文件
    NPOI 设置world表格单元格居中
    NPOI.XWPF.UserModel.XWPFTableCell.SetText()方法不能传入NULL
    a标签不跳转
    mvc 布局页引用布局页 写法
  • 原文地址:https://www.cnblogs.com/javayida/p/13346974.html
Copyright © 2020-2023  润新知