Add sample code for API prefix article (#11959)

* Add sample code for API prefix article

* Update README.md
This commit is contained in:
Michael Pratt 2022-03-29 19:04:34 -06:00 committed by GitHub
parent bc6269085c
commit 1df8b146ba
2 changed files with 54 additions and 0 deletions

View File

@ -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);
}
}
}

View File

@ -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";
}
}