java解决请求跨域的两种方法
java解决请求跨域问题,有以下两种写法
1.使用拦截器,实现javax.servlet.Filter接口
importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; importjavax.servlet.annotation.WebFilter; importjavax.servlet.http.HttpServletResponse; @WebFilter(filterName="CorsFilter",urlPatterns="*.do") publicclassCorsFilterimplementsFilter{ @Override publicvoiddestroy(){ } @Override publicvoiddoFilter(ServletRequestreq,ServletResponseresp,FilterChainchain) throwsIOException,ServletException{ HttpServletResponseresponse=(HttpServletResponse)resp; response.setHeader("Access-Control-Allow-Origin","*");//解决跨域访问报错 response.setHeader("Access-Control-Allow-Methods","POST,PUT,GET,OPTIONS,DELETE"); response.setHeader("Access-Control-Max-Age","3600");//设置过期时间 response.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept,client_id,uuid,Authorization"); response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");//支持HTTP1.1. response.setHeader("Pragma","no-cache");//支持HTTP1.0.response.setHeader("Expires","0"); chain.doFilter(req,resp); } @Override publicvoidinit(FilterConfigarg0)throwsServletException{ } }
如果想用xml的形式配置拦截器,可以删除@WebFilter(filterName="CorsFilter",urlPatterns="*.do"),然后在web.xml中添加下面的配置
CorsFilter com.huaming.filter.CorsFilter CorsFilter *.do
2.使用注解的形式,配置org.springframework.web.filter.CorsFilter,通常springboot项目多数使用这种方式
importorg.springframework.web.filter.CorsFilter; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.web.cors.CorsConfiguration; importorg.springframework.web.cors.UrlBasedCorsConfigurationSource; /** *解决跨域问题springboot所需配置 */ @Configuration publicclassCORSConfiguration{ @Bean publicCorsFiltercorsFilter(){ //1.添加CORS配置信息 CorsConfigurationconfig=newCorsConfiguration(); //1)允许的域,不要写*,否则cookie就无法使用了 config.addAllowedOrigin("*"); config.addAllowedHeader("*");//允许任何头 config.addAllowedMethod("*");//允许任何方法(post、get等) //2)是否发送Cookie信息 config.setAllowCredentials(true); //3)允许的请求方式 config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); //4)允许的头信息 config.addAllowedHeader("*"); //5)配置有效时长 config.setMaxAge(3600*24L); //2.添加映射路径,我们拦截一切请求 UrlBasedCorsConfigurationSourceconfigSource=newUrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**",config); //3.返回新的CorsFilter. returnnewCorsFilter(configSource); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。