Skip to content
Permalink
main
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time
package patterns.sample.controllers;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import patterns.sample.utils.PostPutPatchReturn.User;
import patterns.sample.utils.PostPutPatchReturn.UserRepository;
@RestController
// @ComponentScan("patterns.sample.utils") //to scan packages mentioned
@RequestMapping("/postputpatchreturn") // This means URL start with /demo (after Application path)
public class PostPutPatchReturnController {
@Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
@PostMapping(path = "/add") // Map ONLY POST Requests
public @ResponseBody String addNewUser(@RequestParam String name,
@RequestParam String email,
@RequestParam boolean isReturnObject) {
// @ResponseBody means the returned String is the response, not a view name
// @RequestParam means it is a parameter from the GET or POST request
User n = new User();
n.setName(name);
n.setEmail(email);
User savedUser = userRepository.save(n);
if (isReturnObject) {
Gson gson = new Gson();
return gson.toJson(savedUser);
}
return "Saved";
}
@GetMapping("/all")
public @ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}