Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring app with React UI - how to serve when @EnableWebMvc is applied?

Tags:

java

spring

So I have a React app I want to serve from my Spring app (ala this blog). As part of my gradle build task, I run the npm build command and copy the resulting files to /build/resources/main/static. This works fine and I can access my app at mysite.com/index.html, but I want to control who has access more granularly. As such, I applied @EnableWebMvc to my app, but from there, I can't seem to get my API controller to actually serve the view from the build directory. It seems no matter where I put it, it doesn't like serving directly from /build. Any way to make this work?

The handler looks like:

@Controller
class MyController {
  @RequestMapping("/")
    fun index(): String {
        return "index"
    }
}
like image 624
Rollie Avatar asked Sep 12 '25 18:09

Rollie


1 Answers

As indicated in the Spring Boot documentation, you do not need - in fact, it is not recommended - to use @EnableWebMvc when using Spring Boot. They state, when describing Spring MVC auto-configuration:

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.

And:

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

In the guide, they continue when describing static content handling:

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurer and overriding the addResourceHandlers method.

In your example, following this advice, you can indicate the static resource handling location with something like (sorry, I am not fluent in Kotlin, forgive for write the example in Java):

@Controller
public class MyController implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
      .addResourceHandler("/static/**")
      .addResourceLocations("classpath:/static")
    ;
  }

  @GetMapping(path = "/")
  public String index() {
    return "index";
  }
}

Please, adapt the paths in addResourceHandlers to your needs.

You can of course place this method in an ad hoc @Configuration.

Having said that, if when you say granular you mean security, the best approach you can take is to configure Spring Security and provide the necessary authorization rules: please, see the relevant documentation.

like image 73
jccampanero Avatar answered Sep 14 '25 08:09

jccampanero