I'm new to spring boot framework and i was developing spring boot rest API.
i have endpoint and i have query the database from spring boot
/buy?projectionId=value1&place=value2 // we can add different query parameters here
how to write a controller and service using spring boot.
CodePudding user response:
you can pass multiple params in url like, for example:
http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc
and in order to get this query fields , you can use map like
@RequestMapping(method = RequestMethod.GET, value = "/custom")
public String controllerMethod(@RequestParam Map<String, String> customQuery) {
System.out.println("customQuery = brand " customQuery.get("brand"));
System.out.println("customQuery = limit " customQuery.get("limit"));
System.out.println("customQuery = price " customQuery.get("price"));
System.out.println("customQuery = other " customQuery.get("other"));
System.out.println("customQuery = sort " customQuery.get("sort"));
return customQuery.toString();
}
CodePudding user response:
You can use like below and add more request param.
@GetMapping("/buy") public String buy(@RequestParam("projectionId") long projectionId, @RequestParam("place") String place){ return "some response"; }
API ENDPOINT: http://your hostname:port/buy?projectionId=value1&place=value2
If you have multiple parameter you can prepare one json.
{
"field1": "value1",
"field2": "value2",
"field3": "value",
"field4": "value",
"field5": "value5",
"field6": "value6"
}
**This JSON take as a payload.**
public String buy(@RequestBody String payload){
if(StringUtils.isNotBlank(payload)){
//String convert into class.
Test test = new ObjectMapper().readValue(payload, Test.class);
//Then whatever you want you can use it.
}
return "some response";
}
API ENDPOINT: http://your hostname:port/buy
Request body: { "field1": "value1", "field2": "value2", "field3": "value", "field4": "value", "field5": "value5", "field6": "value6" }
CodePudding user response:
@GetMapping("/api/buy")
@ResponseBody
public String getBuy(@RequestParam String protectId) {
return "ID: " protectId;
}
example request will be
http://localhost:8080/api/buy?protectId=abc