Springboot設(shè)置跨域的三種方式
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
? 作者?|??cchilei?
來(lái)源 |? urlify.cn/ZvM7Jf
66套java從入門到精通實(shí)戰(zhàn)課程分享
方式一(精細(xì)配置)
在需要跨域的整個(gè)Controller或者單個(gè)方法上添加@CrossOrigin注解
方式二(全局配置)
@Configuration
public?class?WebMvcConfig?extends?WebMvcConfigurerAdapter?{
????@Override
????public?void?addCorsMappings(CorsRegistry?registry)?{
????????registry.addMapping("/**")
????????????????.allowedOrigins("*")
????????????????.allowedMethods("POST",?"GET",?"PUT",?"OPTIONS",?"DELETE")
????????????????.maxAge(3600)
????????????????.allowCredentials(true);
????}
}
方式三(通過(guò)filter)
@Component
@WebFilter(urlPatterns?=?"/*",?filterName?=?"authFilter")?//這里的“/*”?表示的是需要攔截的請(qǐng)求路徑
public?class?PassHttpFilter?implements?Filter?{
????@Override
????public?void?init(FilterConfig?filterConfig)?throws?ServletException?{?}
????@Override
????public?void?doFilter(ServletRequest?servletRequest,?ServletResponse?servletResponse,?FilterChain?filterChain)?throws?IOException,?ServletException?{
????????HttpServletResponse?httpResponse?=?(HttpServletResponse)servletResponse;
????????httpResponse.setHeader("Access-Control-Allow-Headers","Origin,?X-Requested-With,?Content-Type,?Accept");
????????httpResponse.setHeader("Access-Control-Allow-Credentials",?"true");
????????httpResponse.addHeader("Access-Control-Allow-Origin",?"http://127.0.0.1:8080");
????????filterChain.doFilter(servletRequest,?httpResponse);
????}
????@Override
????public?void?destroy()?{?}
}


??? ?
感謝點(diǎn)贊支持下哈?
評(píng)論
圖片
表情
