I am Planning to build a web application using Spring Boot as restful service. my spring boot web restful application should be accessible by other application as well. In case if any one accessing the rest service from other application then my application should work as expected.
@Controller
public class GreetingController {
@RequestMapping("/greeting")
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
In above example if call is made from outside of application then the rest service should return JSON output.
One way we can have some variable to distinguish as request variable. But I do not want like that. Please share some standard way.
Appreciate your help.
Idiomatic way is to rely on Accept
request header.
If requester presents Accept: application/json
then return him JSON data (REST API).
If requester provides you with Accept: application/xhtml+xml
return him HTML (web frontend).
Implementation-wise you should is to be done use @RequestMapping
with consumes
argument. You need two methods. If business logic for both paths is the same then in could be reused. Business logic should reside in another method or in separate @Service
. Business logic on its own should not know, care or rely on transport protocol (HTTP), serialization of request response or presentation. Business logic should just work with POJOs and leave serialization to @Controller.
@Controller
@RequestMapping("/greeting")
public class GreetingController {
@RequestMapping(consumes="application/json")
@ResponseBody //required if you want to return POJO (spring will serialize it to response body)
public void rest() {
//return POJO, it will be serialized to JSON. or serialize pojo
directly and return response with manually set body and headers.
}
@RequestMapping(consumes="application/xhtml+xml")
public void html() {
//populate model, return string pointing to HTML to View
}
}