Filter
- Use Servler Filter
Register Filter
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers"); chain.doFilter(req, res); }
Annotation
- @CrossOrigin
- Support Param: origins, maxAge
- Use on Method/Controller
- Method need specify RequestMethod(GET,POST)
- Spring 4.2+
WebMvcConfigurer
Add Globe Configurer, more Spring Style
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://domain.com") .allowedMethods("PUT", "DELETE") .allowedHeaders("header1", "header2", "header3") .exposedHeaders("header1", "header2") .allowCredentials(false).maxAge(3600); }
Old XML Way
- <mvc:cors>
Note
- Spring Security need enable CORS and use Spring Config
- Be Careful with Origin,Method,Header
本文由 Ivan Dong 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Jun 13, 2023 at 09:21 am