Spring Boot with Servlet Context Path – Example

You just want to see an minimal example how to change servlet context path and port in  Spring boot.

This page is for you.

This example is a part of  Spring Boot with all examples

Full Code with Spring Boot 1.5.8.RELEASE:

5_spring-boot-servlet-context.zip

What you need for run this:

  • Maven 3
  • Java 8

What the code will do:

  • Let you change url to http://localhost:<customPort>/<servletContext>

Explain:

This is the file structure:

From this example Spring Boot with Basic REST , you can call Spring Boot with this url:

http://localhost:8080/api/count

You may think:

  • How can I change the port , for example from 8080 to 8081
  • How can I add the servlet context path , for example from / to /test

You just have to add application.properties, like this:

server.contextPath=/test
server.port=8081

Try:

run this in console:

mvn clean package

Then run this to start:

mvn clean spring-boot:run

You should see something like this:

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

.....
.....
2017-12-12 22:03:04.243  INFO 260 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.Annotation
ConfigEmbeddedWebApplicationContext@7595f8d7: startup date [Tue Dec 12 22:03:01 CET 2017]; root of context hierarchy

Open a browswer and try to go to this url:

http://localhost:8081/test/api/count