Solutions to cross domain problems in springboot

Time:2020-11-22

This article mainly introduces the solution of springboot cross domain problem. The example code is introduced in detail, which has certain reference learning value for everyone’s study or work. Friends in need can refer to it

If you do not pay attention to the cross domain problem in springboot, it is easy to cause errors. The version of springboot is 2.13

Front end error message:

Access to XMLHttpRequest at ‘http://localhost:8080/user/loginOn’ from origin ‘http://localhost:8082’ has been blocked by CORS policy:
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

The first is to add a note in each controller: @ crossorigin


import javax.validation.Valid;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController{

You can also add methods, such as this, for specific methods

@CrossOrigin
  @Apioperation (value = user login, notes =)
  @PostMapping("/loginOn")
  public ResponseMessage loginOn(@RequestBody @Valid UserReq userReq){

It is also very troublesome for each controller to write in this way.

The second one is to implement the webmvcconfigurer interface, in which cross domain support is carried out

Previously, webmvcconfigureradapter can be inherited, and springboot2. X version has made it @ derected

We directly implement the interface:

@Configuration
public class WebConfig implements WebMvcConfigurer {

  /**
   *Cross domain support
   * @param registry
   */
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedOrigins("*")
        .allowCredentials(true)
        .allowedMethods("GET", "POST", "DELETE", "PUT")
        .maxAge(3600 * 24);
  }

But using this method, I encountered a pit today. I am going to intercept the user’s request in the interceptor

@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){
        //User defined exception class, where an exception is thrown and handed to the global exception capture class for processing
      Throw new serviceexception ("no permission, please login first!");
    }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 {

  }
}

Global exception capture class:


@RestControllerAdvice
public class GlobleExceptionHandler {
  @ExceptionHandler(value = ServiceException.class)
  public ResponseMessage caughtException(ServiceException e){

    return new ResponseMessage(e.getMsg());
  }
}

Responsemessage is a user-defined unified response information class

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);
  }
}

Through such processing, it is found that the front-end has been reporting cross domain exception problems. At this time, there is a third method

Third, use the corsfilter filter:

Write a mycorsconfig configuration class

@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));
    //Set the order of filters
    bean.setOrder(0);
    return new CorsFilter(source);
  }
}

Finally, the cross domain problem of this demo is solved.

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.