From 1df8b146ba9bc6813fccbf1c4758f1bf90a60581 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Tue, 29 Mar 2022 19:04:34 -0600 Subject: [PATCH] Add sample code for API prefix article (#11959) * Add sample code for API prefix article * Update README.md --- .../controllerprefix/ApiPrefixController.java | 25 ++++++++++++++++ .../ControllerPrefixDemoApp.java | 29 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/controllerprefix/ApiPrefixController.java create mode 100644 spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/controllerprefix/ControllerPrefixDemoApp.java diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/controllerprefix/ApiPrefixController.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/controllerprefix/ApiPrefixController.java new file mode 100644 index 0000000000..7577625955 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/controllerprefix/ApiPrefixController.java @@ -0,0 +1,25 @@ +package com.baeldung.controllerprefix; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import java.util.Random; + +@Controller +@RequestMapping("/api") +public class ApiPrefixController { + + @GetMapping + public ModelAndView route(ModelMap model) { + if(new Random().nextBoolean()) { + return new ModelAndView("forward:/endpoint1", model); + } + else { + return new ModelAndView("forward:/endpoint2", model); + } + } +} + diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/controllerprefix/ControllerPrefixDemoApp.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/controllerprefix/ControllerPrefixDemoApp.java new file mode 100644 index 0000000000..070142d7ac --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/controllerprefix/ControllerPrefixDemoApp.java @@ -0,0 +1,29 @@ +package com.baeldung.controllerprefix; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +@SpringBootApplication +public class ControllerPrefixDemoApp { + public static void main(String[] args) { + SpringApplication.run(ControllerPrefixDemoApp.class, args); + } +} + +@Controller +class EndpointController { + @GetMapping("/endpoint1") + @ResponseBody + public String endpoint1() { + return "Hello from endpoint 1"; + } + + @GetMapping("/endpoint2") + @ResponseBody + public String endpoint2() { + return "Hello from endpoint 2"; + } +}