EDIT --
This is a stupid question - please ignore it. Going away to learn Java properly.
--
I want to create an API that can be used externally, but I also want to create my own front end to the same API.
If I create an MVC controller & a REST controller in the same app, can I call the REST API from the MVC controller without making an "external" http call, which seems a bit wasteful?
(EDIT - originally linked to another question but it ws wrong. Can't find the right one so removed).
Obviously raises the further question of whether I should or not, but that is, I suppose, subjective. As an aside I'd welcome opinion on that.
EDIT 2 (to add some code in response to chrylis)
So if I create a class like this (example copied from a tutorial somewhere)
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
and a rest controller like this which if called directly from the browser will return json data :
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", required=false, defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
Then I call it from my HTML controller like this :
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping("/")
public String home(Model model) {
Greeting gr=new Greeting(1,"Hi");
logger.info(gr.getContent());
model.addAttribute("modelName",gr.getContent());
return "home";
}
}
is that what you mean? It seems to work. The only issue I see is that I'm working on the class directly and not performing the action of the rest api.
Actually, even as I write this I realise this isn't what you meant, I don't think.