被调用方解决-filter解决方案
1、后台程序先执行还是浏览器先判断?
返回的状态码:200表示执行成功 说明请求是先执行,浏览器后判断2、浏览器如何判断?
如果请求跨域,请求头里就会多一个Origin字段,当服务端返回信息的时候,会去判断响应头里是否有对应的字段,如果没有,即出现跨域请求问题,如果有,即允许跨域。
3、后台Filter代码实现
(1)编写CrossFilter过滤器
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中
AjaxserverApplication代码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;
}
}
网友评论