Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redirect to a POST request from one controller to another controller Spring Boot

I have a springboot project with 2 controller files as below:

File1.java
 @PostMapping("/test")
    public String testMap(String s){
         if(s!=null){
           return "found it";
         }
        else {
            // need to go to POST request in another controller
        }
        return "not found";
    }
File2.java
 @PostMapping("/test2")
    public String testMap2(String s){
         if(s!=null){
           return "found it";
         }
        return "not found 2";
    }

I have tried adding java HttpURLConnection lines to send a POST request in File1.java but it does not perform the operations within testMap2, instead it exits with not found

Could you please give some suggestions on how I could accomplish this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use RestTemplate to create another POST request, although I strongly suggest avoiding that.

Since both of these controllers are in the same project, try extracting the common logic into a @Service which should be injected in both controllers.

For example:

File1.java

@RestController
public class MyFirstController {
    private MyBusinessLogic myBusinessLogic;
 
    // Constructor injection
    public MyFirstController(MyBusinessLogic myBusinessLogic) {
        this.myBusinessLogic = myBusinessLogic;
    }
    
    @PostMapping("/test")
    public String testMap(String s){
         if(s!=null){
           return "found it";
         }
        else {
            return myBusinessLogic.doSomething(s);
        }
        return "not found";
    }
}

File2.java:

@RestController
public class MySecondController {
    private MyBusinessLogic myBusinessLogic;
 
    // Constructor injection
    public MySecondController(MyBusinessLogic myBusinessLogic) {
        this.myBusinessLogic = myBusinessLogic;
    }

    @PostMapping("/test2")
    public String testMap2(String s){
         if(s!=null){
           return myBusinessLogic.doSomething(s);
         }
        return "not found 2";
    }
}

Finally create a service for the common logic:

@Service
public class MyBusinessLogic {
   public String doSomething(String s) {
      // common logic goes here
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading