StackTips

How to Add Context Path to a Spring Boot Application

nilan avtar

Written by

Nilanchala,  3 min read,  3.64K views, updated on Sept. 17, 2023

In a Spring Boot application, the context path represents the base URL for accessing your application. By default, it's set to '/',

For example, in the following code snippet

@RestController
@RequestMapping(value = "/products")
public class ProductController {

    @GetMapping
    public List<Product> getProducts() {
        return ResponseEntity.ok(productService.getProducts());
    }

    @GetMapping(value = "/{productId}")
    public Product getProduct(@PathVariable(value = "id") Long id) {        
			//Your service logic goes here..
      return product;
    }

To test this locally, we need to hit

http://localhost:8080/products
http://localhost:8080/products/{productId}

But sometimes you might want to change the path to make it more meaningful or to avoid conflicts. So, how do we do that?”

To change the context path, you need to add the following property to your application.properties file.

server.servlet.context-path=/api/1.0

Alternatively, if you're using the application.yaml file, you can do this


server:
   servlet:
     context-path: '/api/1.0'

Now with this, you run your application and you will be able to access the endpoints with a new URL

http://localhhost:8080/api/1.0/products
http://localhhost:8080/api/1.0/products/{productId}

I hope this helps! Let me know if you have any other questions.

Getting Started with Spring Boot- Beginner's Guide

This course covers the fundamentals of Spring Boot an you will gain the necessary skills to develop various types of applications using the powerful features of the Spring Boot framework.

>> CHECK OUT THE COURSE
nilan avtar

Nilanchala

I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!