栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springmvc和servlet解决跨域问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springmvc和servlet解决跨域问题

springmvc解决跨域:

 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration//自动配置
public class CrosConfig implements WebMvcConfigurer {
    //重新addCorsMappings方法
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")      //添加映射路径,“/**”表示对所有的路径实行全局跨域访问权限的设置
                .allowedOrigins("*")            //开放哪些ip、端口、域名的访问权限
                .allowedMethods( "GET", "POST", "PUT", "OPTIONS", "DELETE")        //开放哪些Http方法,允许跨域访问
                .allowCredentials(true)         //是否允许发送cookie信息
                .maxAge(3600)
                .allowedHeaders("*");            //允许HTTP请求中的携带哪些Header信息
    }
}

以上是springmvc解决跨域问题的方法,下面是原生servlet项目解决跨域问题的方法:

创建一个拦截器,设置响应头

 
import javax.servlet.*;
 import javax.servlet.annotation.WebFilter;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 ​
 @WebFilter("*.action")
 public class CORSFilter implements Filter {
 ​
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {
         Filter.super.init(filterConfig);
     }
 ​
     @Override
     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
         HttpServletResponse resp = (HttpServletResponse) servletResponse;
         HttpServletRequest req = (HttpServletRequest) servletRequest;
         filterChain.doFilter(req,resp);
         resp.setContentType("text/html;charset=UTF-8");
         //禁用缓存,确保网页信息是最新数据
         resp.setHeader("Pragma","No-cache");
         resp.setHeader("Cache-Control","no-cache");
         resp.setHeader("Access-Control-Allow-Origin", "*");
         resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, HEAD, DELETE, PUT");
         resp.setHeader("Access-Control-Max-Age", "3600");
         resp.setHeader("Access-Control-Allow-Headers",
                 "X-Requested-With, Content-Type, Authorization, Accept, Origin, User-Agent, Content-Range, Content-Disposition, Content-Description");
 ​
         resp.setDateHeader("Expires", -10);
     }
 ​
     @Override
     public void destroy() {
         Filter.super.destroy();
     }
 }

@WebFilter("*.action")这里的路径根据实际项目更改

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/343766.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号