Javaweb下的跨域问题

Deathlightning

       由于浏览器同源访问的限制,前端在使用ajax进行请求时会出现跨域问题,只要端口不同,主机不同服务调用一定跨域,在spring里面,有个@CrossOrigin注解可以解决跨域问题,但是在我的实践中发现并不好用前几天用spring boot写后台出现跨域,之前有用的解决方案全部失效,很玄学的问题。现在我想用一种通用的解决方案来实现:

public class OriginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 处理跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        httpServletResponse.setHeader("X-Powered-By", "Tomcat");
        httpServletResponse.setHeader("Content-Type", "text/html;charset=UTF-8");
        httpServletResponse.setHeader("maxAge", "10000");

        request.setAttribute("Access-Control-Request-Headers", "*");
        filterChain.doFilter(request, response);
    }
}

如果是springboot还需要在本类上加注解

@Component
@WebFilter(urlPatterns = "/", filterName = "myOriginFilter")
@Order(1)//指定过滤器的执行顺序,值越大越靠后执行

主类上加上@ServletComponentScan

若是普通javaweb项目写配置文件就好

个人见解:跨域这种安全性问题真的不能交给前端去控制,我们的前端一直想去用jsonp去解决跨域被我挡回去了,前端真的控制不了安全问题

阅读 3.1k
41 声望
2 粉丝
0 条评论
41 声望
2 粉丝
文章目录
宣传栏