📜  spring boot base url - Java (1)

📅  最后修改于: 2023-12-03 15:20:12.478000             🧑  作者: Mango

Spring Boot Base URL - Java

If you're working with Spring Boot applications, you may occasionally need to define a "base URL" that your application will use as a reference point when handling incoming requests. In this guide we'll explore how to define and use a base URL in a Spring Boot application using Java.

Defining a Base URL

To define a base URL for a Spring Boot application, we need to modify the application.properties file that is typically located in the src/main/resources/ folder. We can add the following line to that file:

server.servlet.context-path=/my-app

This tells Spring Boot to prefix all request mappings with "/my-app", effectively defining a base URL for the application.

Alternatively, we can also define the base URL programmatically in a Spring Boot @Configuration class:

@Configuration
public class AppConfig {
 
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        return server -> server.setContextPath("/my-app");
    }
}

Note that "/my-app" can be replaced with any string representing the desired base URL.

Using a Base URL

Once we've defined a base URL, we can use it to define our controllers and request mappings. For example, let's say we have a controller that handles requests to "/hello". Without a base URL, we would define the controller like this:

@RestController
public class HelloController {
 
    @GetMapping("/hello")
    public String hello() {
        return "Hello World";
    }
}

With a base URL of "/my-app", we would modify the controller like this:

@RestController
@RequestMapping("/hello")
public class HelloController {
 
    @GetMapping
    public String hello() {
        return "Hello World";
    }
}

Note that the @RequestMapping annotation now specifies "/hello", which is relative to the base URL of "/my-app".

Conclusion

By defining a base URL for a Spring Boot application, we can more easily design and manage our request mappings. Whether implementing the base URL in application.properties or through a @Configuration class, the process is straightforward and can lead to more organized and scalable applications.