【发布时间】:2017-12-01 14:23:01
【问题描述】:
在我们的 Spring Boot 应用程序中,我们在 Quality 环境中进行了第一次部署,现在我们希望简化定义 URL 以接受来自 FrontEnd 应用程序的请求。
我们用 maven 构建我们的应用程序,然后我们用命令执行它
java -Dspring.profiles.active=prod -jar myapp-0.0.1-SNAPSHOT.jar
我们认为我们可以在application.properties/application-prod.properties 文件上设置 URL,但这不起作用,因为在执行时它是空的。另一种解决方法是以某种方式获取我们在运行应用程序时传递的参数-Dspring.profiles.active=prod,然后获取一个或另一个 URL,但这似乎有点脏......
那么你们会怎么做呢?在谷歌上没有找到任何东西给我留下了深刻的印象,显然人们有不同的解决方法,或者我搜索的方式错误。
编辑 跨域信息: 这就是我们最初实现它的方式。
@CrossOrigin(origins = BasicConfiguration.CLIENT_URL)
这就是我们现在想要使用 Spring Security 过滤器的方式
public class CorsFilter implements Filter, ApplicationContextAware {
@Value("${urlServer}")
private String urlServer;
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", urlServer);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Expose-Headers", "Location");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}
当然 urlServer 是在 application.properties 中定义的,并带有相应的元数据。
编辑 2 我如何初始化过滤器:
@Bean
public FilterRegistrationBean corsFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new CorsFilter());
registration.addUrlPatterns("/sessionLogin");
return registration;
}
【问题讨论】:
-
你能分享你设置 CORS url 的代码吗?实际上它应该与 application.properties 完美配合,这是正确的做法
-
stackoverflow.com/questions/44797127/… 这样您就可以定义来自外部文件的属性,覆盖来自 application.properties 的属性
-
你如何创建你的 CorsFilter 对象?我猜你只是像
new CorsFilter()那样创建它,所以它不是一个spring bean,它不是由spring 上下文管理的。这就是为什么你的财产不能被注入 -
我添加了初始化@Leffchik
标签: spring jakarta-ee spring-boot cors