被调用方解决-filter解决方案
1、后台程序先执行还是浏览器先判断?
2、浏览器如何判断?
3、后台Filter代码实现
(1)编写CrossFilter过滤器
package com.ajax.server.filter;
import javax.servlet.*;
importjavax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CrossFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponseservletResponse, FilterChain filterChain) throws IOException, ServletException{
HttpServletResponse res = (HttpServletResponse) servletResponse;
res.addHeader("Access-Control-Allow-Origin","http://localhost:8082");
res.addHeader("Access-Control-Allow-Methods","GET");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
(2)把过滤器注入到spring container中
package com.ajax.server;
import com.ajax.server.filter.CrossFilter;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importorg.springframework.boot.web.servlet.FilterRegistrationBean;
importorg.springframework.context.annotation.Bean;
@SpringBootApplication
public class AjaxserverApplication {
publicstatic void main(String[] args) {
SpringApplication.run(AjaxserverApplication.class,args);
}
@Bean
publicFilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBeanfilterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setFilter(newCrossFilter());
returnfilterRegistrationBean;
}
}