springboot中怎么解决跨域问题,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
博望ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!
第一种:是在每个Controller里,加上注解:@CrossOrigin
import javax.validation.Valid; @CrossOrigin @RestController @RequestMapping("/user") public class UserController{
也可以在方法上加上,比如这样,这样针对具体的方法
@CrossOrigin @ApiOperation(value = "用户登录",notes = "") @PostMapping("/loginOn") public ResponseMessage loginOn(@RequestBody @Valid UserReq userReq){
每一个Controller这样写也是很麻烦。
第二种:是实现WebMvcConfigurer接口,在接口中进行跨域支持
以前可以继承WebMvcConfigurerAdapter,springboot2.x版本已经将其@Deprecated
我们直接实现接口:
@Configuration public class WebConfig implements WebMvcConfigurer { /** * 跨域支持 * @param registry */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .maxAge(3600 * 24); }
但使用这种方法,我今天遇到一个坑,我准备在拦截器里面对用户的请求进行拦截
@Component public class RequestInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object loginUser = request.getSession().getAttribute("token"); if(loginUser == null){ //自定义的异常类,这里抛出异常,交给全局异常捕捉类处理 throw new ServiceException("没有权限,请先登录!"); }else{ return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
全局异常捕捉类:
@RestControllerAdvice public class GlobleExceptionHandler { @ExceptionHandler(value = ServiceException.class) public ResponseMessage caughtException(ServiceException e){ return new ResponseMessage(e.getMsg()); } }
ResponseMessage 是自定义的统一的响应信息类:
ResponseMessage
@Data public class ResponseMessage { private Integer Code; private String msg; private Integer count; private Object data; public ResponseMessage(Object data) { this.data = data; } public ResponseMessage(String msg) { this.msg = msg; } public ResponseMessage(Integer code, String msg) { Code = code; this.msg = msg; } public ResponseMessage(Integer code, String msg, Integer count) { Code = code; this.msg = msg; this.count = count; } public ResponseMessage(Integer code, String msg, Integer count, Object data) { Code = code; this.msg = msg; this.count = count; this.data = data; } public static ResponseMessage success(String msg){ return new ResponseMessage(200,msg); } public static ResponseMessage fail(Integer code,String msg){ return new ResponseMessage(code,msg); } }
通过这样的处理发现,前端一直报跨域异常问题,这时候有了第三种方法
第三种:使用CorsFilter过滤器:
写一个MyCorsConfig 配置类
@Configuration public class MyCorsConfig { @Bean public CorsFilter corsFilter() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setAllowCredentials(true); corsConfiguration.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", corsConfiguration); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); //设置过滤器的顺序 bean.setOrder(0); return new CorsFilter(source); } }
看完上述内容,你们掌握springboot中怎么解决跨域问题的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!