Search code examples
javaspring-bootfrontend

How to connect spring boot backend with frontend?


I can develop a simple REST apllication (CRUD operations, for example) on Spring Boot, but how to connect it with HTML pages. I have already used Freemarker + Bootstrap. But the options are limited, when it concerns the design part. What is the next step? What technologies or platform should I use?


Solution

  • The simplest way is to add annotation @CrossOrigin in your controller. It is enough for very little application but it is better to create special configuration for this.

    You create a package configuration on the same level src/main in java/(your project name). In this package, you create a class WebConfig:

    package yourProject.configuration;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        
    
        @Value("${project.cors.allowed-origins}")
        private String[] allowedOrigins;
    
        @Value("${project.cors.allowed-methods}")
        private String[] allowedMethods;
        
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            configurer.setUseTrailingSlashMatch(false);
    
        }
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins(allowedOrigins).allowedMethods(allowedMethods);
        }
    

    And in application.properties you add origin of your front (in my case it is vue application) and methods:

    # Cors properties:
    
    project.cors.allowed-origins=http://localhost:5173
    project.cors.allowed-methods=POST,GET,PUT,PATCH,DELETE