说明
针对前后端分离场景下的一种跨域方案,如果不使用如nginx或者springboot的zuul网关等方案,可以采用 httpproxy 方案。
在需要对接接口的web服务加入以下配置:
- 需要引入的依赖:
<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
<version>1.10</version>
</dependency>
- 编写配置方法类
@Configuration
public class ProxyServletConfiguration implements EnvironmentAware {
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new ProxyServlet(), propertyResolver.getProperty("servlet_url"));
servletRegistrationBean.addInitParameter("targetUri", propertyResolver.getProperty("target_url"));
servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, propertyResolver.getProperty("logging_enabled", "false"));
return servletRegistrationBean;
}
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "proxy.solr.");
}
}
- 在application.yml中配置
server:
port: 8088
proxy:
solr:
servlet_url: /project/v1/*
target_url: http://localhost:8092/project/v1
配置说明:
servlet_url : 对外可以访问的匹配路径,如前端js 在web服务访问后端服务的一个接口,可以不加域名或者ip port;
target_url : 指向后端服务的根服务地址。
更多,请关注:
springboot 技术实践总结
网友评论