解决跨域问题的方法挺多的。该方法只是本人用过,做个记录。
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
* 拦截器,允许跨域
* @author zhang
* @date 2018年10月10日,下午2:05:39
*/
@Component
public class CrosInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
httpServletResponse.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
String method= httpServletRequest.getMethod();
if (method.equals("OPTIONS")){
httpServletResponse.setStatus(200);
return false;
}
return true;
}
}
import javax.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置拦截器
* @author zhang
* @date 2018年10月10日,下午2:09:52
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private CrosInterceptor cros;
/* (non-Javadoc)
* @see org.springframework.web.servlet.config.annotation.WebMvcConfigurer#addInterceptors(org.springframework.web.servlet.config.annotation.InterceptorRegistry)
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(cros).addPathPatterns("/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
}