相同与方法您。
@Configuration
public class ManagerWarInit extends WebMvcConfigurerAdapter {
...
private static final String[] SUPPORT_METHODS = new String[] {
HttpMethod.HEAD.name(),
HttpMethod.OPTIONS.name(),
HttpMethod.GET.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name()
};
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods(SUPPORT_METHODS)
.exposedHeaders("Set-Cookie");
}
}
和globalException
@ControllerAdvice
public class ManagerGlobalException {
// @CrossOrigin(...)
@ExceptionHandler(NotLoginException.class)
public void noLogin(NotLoginException e, HttpServletResponse response)
throws IOException {
if (LOG.isDebugEnabled())
LOG.debug(e.getMessage());
if (RequestUtils.isAjaxRequest()) {
RequestUtils.toJson(notLogin(), response);
} else {
response.sendRedirect("hxxp://www.xxx.com");
}
}
}
但跨域通过浏览器(Chrome等)
XMLHttpRequest cannot load hxxp://127.0.0.1:8080/url... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'hxxp://127.0.0.1:3000' is therefore not allowed access.
试图上的ExceptionHandler添加@CrossOrigin
注解仍然有此错误调用错误
我处理这个现在
@ControllerAdvice
public class ManagerGlobalException {
@ExceptionHandler(NotLoginException.class)
public String notLogin(NotLoginException e) throws IOException {
if (LOG.isDebugEnabled())
LOG.debug(e.getMessage());
if (RequestUtils.isAjaxRequest()) {
return "forward:/not-login";
} else {
return "redirect:hxxp://www.xxx.com";
}
}
}
添加映射
@RestController
public class IndexController {
@RequestMapping(value = "/not-login")
public JsonResult notLogin() {
return JsonResult.notLogin();
}
}
CORS是跨域请求守卫的协议,您应该@ControllerAdvice收集器例外,它们是CORS检查之后的一个步骤,什么是您正在使用的servlet容器?而这是请求的方法类型? –
@AmerQarabsa我正在使用嵌入式的tomcat。任何方法类型似乎都失败了......但我最初使用OPTIONS。 – FMC