【Java】Java中解决跨域问题的几种方法(建议收藏)
在Java中解决跨域问题,可以通过以下几种方法:
- 通过Nginx等代理服务器配置CORS头部:
location / {
proxy_pass http://your_backend;
proxy_set_header Access-Control-Allow-Origin *;
proxy_set_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
proxy_set_header Access-Control-Allow-Headers 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
- 在Spring框架中,可以使用
@CrossOrigin
注解:
@CrossOrigin(origins = "*")
@RestController
public class MyController {
// ...
}
- 在Spring Security中,可以配置CORS:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
- 在Spring Boot中,可以在
application.properties
或application.yml
中配置:
# application.properties
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.web.cors.allowed-origins=*
spring.web.cors.allowed-methods=GET, POST, OPTIONS
- 在Servlet Filter中手动设置CORS头部:
@WebFilter
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
// ...
chain.doFilter(request, response);
}
}
选择合适的方法根据你的应用架构和需求进行配置即可。
评论已关闭