Issue
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?
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
}
}
Answered By - Ervin Szilagyi
Answer Checked By - Marilyn (JavaFixing Volunteer)