Solutions to cross domain problems in springboot


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;
public class UserController{

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

  @Apioperation (value = user login, notes =)
  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:

public class WebConfig implements WebMvcConfigurer {

   *Cross domain support
   * @param registry
  public void addCorsMappings(CorsRegistry registry) {
        .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

public class RequestInterceptor implements HandlerInterceptor {
  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!");
      return true;

  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {


Global exception capture class:

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


public class ResponseMessage {
  private Integer Code;
  private String msg;
  private Integer count;
  private Object data;

  public ResponseMessage(Object 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; = 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

public class MyCorsConfig {

  public CorsFilter corsFilter() {

    CorsConfiguration corsConfiguration = new CorsConfiguration();

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", corsConfiguration);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    //Set the order of filters
    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.