Java server for Android applications

I need to make a server in java that will work with the database and perform other functions. The choice fell on the server based on the REST API. The main thing is that it must respond to HTTP requests coming from the client Android application. The client application itself contains a WebView that displays the site located locally. I send the request using JS, but no matter how hard I try, the result is the same...

Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Tell me how to fix it. It is possible to completely change architecture or toolkit. The main thing is that the server is written in Java.

Author: Alexander Tsapkov, 2020-04-28

1 answers

Adding CORS to Spring:

  1. You can add the @CrossOrigin annotation in front of the controller.
  2. You can declare it globally by adding a Bean in the main class of the application. Example:
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfig(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}
 -1
Author: Alexander Tsapkov, 2020-04-29 08:00:18