Skip to content

Instantly share code, notes, and snippets.

@sachintaware
Forked from elevenrax/SpringSTSCheatSheet.java
Created September 15, 2018 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachintaware/08a4c8b9ca8fc1a6e04bf82247c2c2f9 to your computer and use it in GitHub Desktop.
Save sachintaware/08a4c8b9ca8fc1a6e04bf82247c2c2f9 to your computer and use it in GitHub Desktop.
Spring STS Cheat Sheet
/**
* Controller Class
* Contains Mappings and HTTP Methods
*/
@RestController
public class TopicController {
@Autowired
private TopicService topicService;
// Allows full gamut of methods
@RequestMapping("/topics");
public List<Topic> getAllTopics() {
return topicService.getAllTopics();
}
// Maps id to paramater id. Allows all methods
@RequestMapping("/topics/{id}")
public Topic getTopic(@PathVariable String id) {
return topicService.getTopic(id);
}
// Makes new topic
// Post requests to /topics only
@RequestMapping(method=RequestMethod.POST, value="/topics")
public void addTopic(@RequestBody Topic topic) {
topicService.addTopic(topic);
}
// Updates topic
// Put method
@RequestMapping(method=RequestMethod.PUT, value="/topics/{id}")
public void updateTopic(@PathVariable String id, @RequestBody Topic topic) {
topicService.updateTopic(id, topic);
}
// Delete
@RequestMapping(method=RequestMethod.DELETE, value="/topics/{id}")
public void deleteTopic(@PathVariable String id) {
topicService.deleteTopic(id);
}
}
/**
* Service.
* Holds business logic.
*/
@Service
public class TopicService {
// Trivial dataset to test
private List<Topic> topics = new ArrayList<>(Arrays.asList(
new Topic("spring", "Spring Framework", "Spring Framework Description"),
new Topic("java", "Core Java", "Spring Framework Description"),
new Topic("javascript", "JavaScript", "JavaScript Description")
));
public List<Topic> getAllTopics() {
return topics;
}
public Topic getTopic(String id) {
return topics.stream().filter(t -> t.getId().equals(id)).findFirst().get();
}
public void addTopic(Topic topic) {
topics.add(topic);
}
public void updateTopic(String id, Topic topic) {
for (int i = 0; i < topic.size(); i++) {
Topic t = topics.get(i);
if (t.getId().equals(id)) {
topics.set(i, topic);
return;
}
}
}
public void deleteTopic(String id) {
topic.removeIf(t -> t.getId().equals(id));
}
}
/**
* Model
* For Topics
*/
public class Topic {
private String id;
private String name;
private String description;
public Topic() {}
public Topic(String id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
// Setters/Getters: Just a regular old Java Class.
}
/**
* Start the Spring App
*
*/
public class MyApiApp {
// Look how easy it is to use SpringBoot
public static void main(String[] args) {
SpringApplication.run(MyApiApp.class, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment